Using the getElementsByClassName method

The getElementsByClassName method will return elements of the same class as a NodeList and not an ArrayNodeList is not exactly an Array; however, it is iterable, and easily convertible into Array as well:

<span class="tag">Hello</span><span class="tag">Hi</span><span class="tag">Wohoo!</span><script>const tags = document.getElementsByClassName('tag'); // This is a NodeList (not Array)try {  tags.map(tag => console.log(tag)); // ERROR! map is not a function} catch(e) {  console.log('Error ', e);}[...tags].map(tag => console.log(tag)); // No error</script>

As said previously, tags is actually a NodeList. First, we use a destructuring operator and surround it with square brackets to actually convert it ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.