- Home
- /
- JS getElementsByClassName
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS getElementsByClassName
JavaScript getElementsByClassName()
The getElementsByClassName()
method allows you to select multiple HTML elements that share the same class name. It returns a live collection of elements, meaning it updates in real time as the DOM changes.
Syntax
document.getElementsByClassName("className");
"className"
is the exact name of the class you’re targeting.It returns an HTMLCollection, which behaves like an array but is not exactly an array.
Example HTML
Note 1
Note 2
Note 3
Example JavaScript
let notes = document.getElementsByClassName("highlight");
for (let i = 0; i < notes.length; i++) {
notes[i].innerHTML = `Updated Note ${i + 1}`;
}
This code updates each element with the class highlight
to show new content dynamically.
Key Features
Feature | Details |
---|---|
Returns | A live HTMLCollection of all matching elements |
Target by class | Useful when many elements share the same styling or role |
Live Collection | Automatically updates when DOM changes |
Index-based access | You can loop using a regular for loop or for...of with Array.from() |
Important Notes
getElementsByClassName()
is case-sensitive."Box"
and"box"
are different.It does not return an array. You can convert it to an array using
Array.from()
if you need array methods.
let divs = Array.from(document.getElementsByClassName("highlight"));
divs.forEach(div => {
div.style.backgroundColor = "#f0f0f0";
});
Summary
Great for selecting multiple elements with a shared class.
Returns a live list – reflects real-time DOM changes.
Can be looped through or converted to an array.