Trying to break away from the for loop
Memo to self: I’m working with the DOM (Document Object Model). I need to select all the <section> elements in the document. Then I need to iterate over the results to change each element in some way. I’ve done this before. My first instinct is to reach for the trusty ol’ for loop…
Why not! So I make my selection and try out map(). And receive an error…
let x = document.getElementsByTagName('section');let newArray = x.map(el => el.textContent = 'new content');
Uncaught TypeError: x.map is not a function… 😨
Ugh! It’s very tempting to go back to the for loop right now and leave this error far behind, but I’m not giving up that easily. I’m going to try out forEach(). I didn’t need a new array of results returned anyway. I just need to make changes to each element. But I receive the same type of error…
x.forEach(el => el.textContent = 'new content');
Uncaught TypeError: x.forEach is not a function… 😨 😨
So what’s the problem?
What about using document.querySelectorAll()? Good question, and the answer is yes and no. I still wouldn’t have an array. This approach will return a Node List. Node Lists do have a few built-in methods including forEach(), but they do not support map().
Spread Syntax to the rescue!
let spreadArray = [...x];
In summary, remember selecting from the DOM with document.getElementsByTagName(), document.getElementsByClassName(), or document.querySelectorAll() will not return an array of results. Yet, one quick line of code utilizing spread syntax will create an array from those results. And arrays have so many methods to choose from including map() and forEach().