How to select DOM 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() 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.