How to select elements by class name using JavaScript

published: 27 Jun 2022

2 min read

How to select elements by class name using JavaScript

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.

How to select elements by class name using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array