Understanding getElementsByClassName() in JavaScript

While exploring the DOM in JavaScript, I came across several methods such as getElementById
, getElementsByClassName
, and others. I wanted to dynamically change the background color of elements on a webpage and decided to experiment with getElementsByClassName()
.
My First Attempt:
let boxes = document.getElementsByClassName('box');
boxes.style.backgroundColor = 'blue';
This didn’t work — and I soon realized why.
What Worked:
When I tried using getElementById
instead, it worked as expected:
let box = document.getElementById('box1');
box.style.backgroundColor = 'blue';
Why getElementsByClassName
Didn't Work Initially
The key point is that getElementsByClassName()
returns an HTMLCollection — essentially a collection (similar to an array) of all elements with the specified class. It does not return a single element. Therefore, we cannot directly apply a style to the whole collection like we do with an individual element.
The Correct Approach:
To apply styles to all elements returned by getElementsByClassName()
, we need to loop through the collection:
const collection = document.getElementsByClassName('box');
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = 'black';
}
This worked perfectly! Each element with the class box
now had its background color changed.
Key Takeaway:
getElementById()
returns a single element — you can apply styles or changes directly.getElementsByClassName()
returns an HTMLCollection — you need to loop through it to apply changes to each element individually.
Understanding the return type of DOM methods is crucial when manipulating elements in JavaScript. This small experiment helped me understand the structure of the DOM more clearly, and how to work with collections of elements effectively.
Subscribe to my newsletter
Read articles from Vishakha Baghel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
