How to get elements by class name in JavaScript

Getting elements by class name allows you to select and manipulate multiple elements that share the same CSS class, perfect for batch operations. As the creator of CoreUI, a widely used open-source UI library, I’ve used class-based selection extensively for styling updates and event handling across multiple components. From my expertise, document.getElementsByClassName() is the most straightforward method for selecting elements by class. This approach returns a live HTMLCollection that automatically updates when the DOM changes.

Use document.getElementsByClassName() to select all elements with a specific class name.

const elements = document.getElementsByClassName('btn')
elements[0].style.backgroundColor = 'blue'

Here document.getElementsByClassName('btn') returns an HTMLCollection containing all elements with the class btn. You can access individual elements using array-like syntax elements[0] or iterate through them with a loop. The collection is live, meaning it automatically reflects any DOM changes.

Best Practice Note:

The returned HTMLCollection is array-like but not a true array. Use Array.from() or spread operator to convert it for array methods. This is the same approach we use in CoreUI for applying styles and behaviors to groups of similar components.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to set focus on an input field after rendering in React
How to set focus on an input field after rendering in React

How to loop through an array in JavaScript
How to loop through an array in JavaScript

What is Double Question Mark in JavaScript?
What is Double Question Mark in JavaScript?

JavaScript Template Literals: Complete Developer Guide
JavaScript Template Literals: Complete Developer Guide

Answers by CoreUI Core Team