Select Multiple Elements by Class Name
You'll learn how to grab all elements with a shared CSS class name at once, even if they're scattered across your page.
What Is getElementsByClassName()?
While getElementById() finds one unique element, getElementsByClassName() is like casting a wider net—it finds all elements that share the same class name. Think of it like calling out "everyone wearing a red shirt" in a crowded room. Multiple people respond, not just one.
This method returns an HTMLCollection, which is a live, array-like list of matching elements. "Live" means if you add or remove elements with that class name later, the collection automatically updates.
How It Works
// HTML: <div class="card">...</div>
// <div class="card">...</div>
// <article class="card">...</article>
const allCards = document.getElementsByClassName('card');
console.log(allCards.length); // 3
console.log(allCards[0]); // First <div class="card">
console.log(allCards[1]); // Second <div class="card">
Notice you don't include the dot (.) like in CSS—just the class name itself.
It's Live and Updates Automatically
const buttons = document.getElementsByClassName('btn');
console.log(buttons.length); // Let's say 2
// Later, JavaScript adds a new button with class="btn"
// buttons.length is now 3 automatically!
The HTMLCollection stays connected to the DOM and reflects changes in real-time.
Important Notes
- Returns an HTMLCollection (array-like but not a true array)
- Access items by index:
elements[0],elements[1] - Always returns a collection, even if only one element matches
- If nothing matches, you get an empty collection (length of 0)
Key Takeaway: document.getElementsByClassName() selects all elements with a specific class name and returns a live HTMLCollection that automatically updates when the DOM changes.