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.