Edit Template
  • Home
  • /
  • JS getElementsByClassName
Edit Template
  • 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

				
					<div class="highlight">Note 1</div>
<div class="highlight">Note 2</div>
<div class="highlight">Note 3</div>

				
			

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

FeatureDetails
ReturnsA live HTMLCollection of all matching elements
Target by classUseful when many elements share the same styling or role
Live CollectionAutomatically updates when DOM changes
Index-based accessYou 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.

Scroll to Top