getElementsByClassName Method in JavaScript

Key Features of the getElementsByClassName Method:

Syntax


document.getElementsByClassName("className");

The getElementsByClassName method in JavaScript is used to access all elements with a specified class name. It returns a live HTMLCollection of elements, which can be used to dynamically modify content, styles, and attributes of multiple elements at once.

Key Features of the getElementsByClassName Method:

Example 1: Changing Text Content for Multiple Elements

This example shows how to change the text content of all elements with a specified class using getElementsByClassName:

Example


var elements = document.getElementsByClassName("exampleClass");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "Updated Content";
                }

Output

All elements with the class "exampleClass" will have their content changed to "Updated Content".

Example 2: Changing Styles of Multiple Elements

In this example, we change the style of multiple elements with a specific class using getElementsByClassName:

Example


var elements = document.getElementsByClassName("highlight");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "blue";
elements[i].style.fontWeight = "bold";
                }

Output

All elements with the class "highlight" will have their text color changed to blue, and font set to bold.

Example 3: Adding Event Listeners to Multiple Elements

This example demonstrates how to add an event listener to multiple elements using getElementsByClassName:

Example


var buttons = document.getElementsByClassName("clickButton");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
alert("Button clicked!");
});
}

Output

All buttons with the class "clickButton" will display an alert with the message "Button clicked!" when clicked.

Example 4: Toggling Classes on Multiple Elements

This example shows how to toggle a class for multiple elements with getElementsByClassName:

Example


var elements = document.getElementsByClassName("toggleClass");
for (var i = 0; i < elements.length; i++) {
elements[i].classList.toggle("active");
                }

Output

All elements with the class "toggleClass" will toggle the "active" class, adding it if absent and removing it if present.

Additional Example: Changing Attributes of Multiple Elements

This example demonstrates changing an attribute of multiple elements with the class "imageClass":

Example


var images = document.getElementsByClassName("imageClass");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("alt", "Updated image description");
}

Output

All images with the class "imageClass" will have their alt attribute updated to "Updated image description".