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) {

Since HTMLCollection is neither a NodeList nor an array, you can not use the forEach() method to iterate over its elements. Therefore, we used the for...of statement.

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')

Read this 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.