Skip to content
Advertisement

Array.from() not converting nodeList into an array

I’ve created a nodeList of list elements using createElement(). Then I’ve used Array.from() to convert the nodeList in question into array I can iterate over. I want to apply a different width according to the value of the index. If index is even width of 300px else width of 500px. However, the console returns “Cannot read property ‘style’ of undefined at bottlesOnTheWall”.

I’ve also used […] to turn my nodeList into an array but without success either. My guess is that is not a nodeList in the first place, which means it can’t be converted into an array. At least not using either of these approaches.

I was wondering if someone could point out where I’ve gone wrong and fix my code. I’ve been spending more time that’s healthy trying to do so.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

Array.from needs a variable with an implemented Symbol.iterator. A single element does not have it, but a list of elements, which is not given here.

Then you have some more issues:

  • Global variables, but only used in a single function. Just move all varaibles inside of the function.

  • Take a parameter for count.

  • Take a single loop without collecting all texts first in an array and then iterate again for creating elements. The only purpose is to use a layer model to separate the data collection from the presentation layer.

  • Finally take a conditional (ternary) operator ?: for width.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement