The getElementsByClassName() method provides a quick way to select all DOM elements that contain a specific CSS class in JavaScript. It returns an HTMLCollection object which is an array-like object containing a collection of HTML elements.

The following example demonstrates how you can use the getElementsByClassName() method to select and iterate over all HTML elements that have the active class name:

const elems = document.getElementsByClassName('active');

// iterate over all HTML elements
for (const el of elems) {
    console.log(el.innerText);
}

Since HTMLCollection is neither a NodeList nor an array, you can not use the forEach() loop over its elements. Therefore, I have use the for...of statement in the above example.

The getElementsByClassName() method works in all modern and old browsers including Internet Explorer 9 and higher. Since it can only be used to select elements by class name, its usage is limited.

If you want more flexibility to select DOM elements by any arbitrary CSS selectors, use the querySelectorAll() method instead:

const elems = document.querySelectorAll('active');

Take a look at how to select DOM elements guide to learn more about different ways of getting DOM elements in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: