DEV Community

Discussion on: JavaScript DOM - Part 6 - Get Elements By TagName [video + article]

Collapse
 
andogq profile image
Tom Anderson

Nice article! Just thought I'd add to the iteration bit:

Any DOM selector that returns mutlple objects (getElementsByTagName, getElementsByClassName ect) return a HTMLCollection object, which is different from an array, lacking all of the useful prototype functions like forEach which would make iteration easier and cleaner as opposed to a for loop.
To get around this, I like to use the ES6 spread operator on the result of the DOM function, effectively 'converting' it into a normal JS array, allowing me to operate and iterate over it as usual! See below for an example!

let para = [...document getElementsByTagName("p")];
para.forEach(p => {
    ... 
});
Collapse
 
developertharun profile image
Tharun Shiv

That's a beauty! Thanks for contributing 🙂