H.dev

getElementsByClassName()

Selecting Groups of Elements

While IDs are unique to a single element, CSS class names are designed to be shared among multiple elements (like a group of cards, or multiple list items).

To select all elements that share the same class, we use document.getElementsByClassName().

Returning a Collection

Notice the "s" in "Elements"? Because this method expects to find multiple items, it does not return a single HTML node. Instead, it returns an HTMLCollection (which looks and acts a lot like an Array, but isn't a true JavaScript Array).

HTML:

<p class="warning-text">Don't do this!</p>
<p class="normal-text">This is fine.</p>
<p class="warning-text">Seriously, stop!</p>

JavaScript:

let warnings = document.getElementsByClassName("warning-text");

console.log(warnings.length); // 2
console.log(warnings[0]);     // Returns the first <p> element

Looping Through the Collection

Because it returns a collection, you cannot apply a change to all of them at once simply by doing warnings.style.color = "red". You must loop through the collection and change them one by one.

let warnings = document.getElementsByClassName("warning-text");

for (let i = 0; i < warnings.length; i++) {
    warnings[i].style.color = "red";
}

💡 Himanshu's Tip:

An HTMLCollection is "live". This means if your JavaScript code adds a new element with the class "warning-text" to the page later on, the warnings variable we created above will automatically update to include it!

Interview Questions

  1. What data type does getElementsByClassName return?
  2. Why can't you use traditional Array methods like map() or forEach() directly on an HTMLCollection?
  3. How do you access the second element in an HTMLCollection returned by this method?

Design & Developed by Himanshu Dubey © 2026