JavaScript getElementsByClassName()

The JavaScript getElementsByClassName() method is used to select HTML elements based on their class name. It allows you to access multiple elements that share the same class and modify their content, styles, or other properties using JavaScript.

For example, if several paragraphs have the same CSS class, you can use getElementsByClassName() to select them and change their text color simultaneously.

In this tutorial, you will learn what getElementsByClassName() is, its syntax, how it works, practical examples, common mistakes, and best practices.

What Is getElementsByClassName() in JavaScript?

The getElementsByClassName() method is a DOM method that returns a live HTMLCollection containing elements with the specified class name.

Unlike getElementById(), which selects an element by its ID, getElementsByClassName() can select multiple elements that share the same class.

Consider the following HTML example:

<p class="message">First paragraph</p>
<p class="message">Second paragraph</p>
<p class="message">Third paragraph</p>

You can select all three paragraphs using JavaScript:

const elements = document.getElementsByClassName("message");

console.log(elements);

The returned collection contains all three paragraph elements because they share the message class.

This method is useful when you want to apply the same operation to multiple HTML elements.

Syntax of getElementsByClassName()

The syntax of the getElementsByClassName() method is:

document.getElementsByClassName("className");

Here is what each part means:

ComponentDescription
documentRepresents the current HTML document.
getElementsByClassName()Selects elements using their class names.
"className"The class name used to find matching elements.

For example:

document.getElementsByClassName("product");

This statement selects all elements in the document that have the product class.

Important: Do not include the dot (.) before the class name. The dot is used in CSS selectors, but getElementsByClassName() accepts the class name directly.

How to Use getElementsByClassName() in JavaScript

Let’s create a simple HTML page containing multiple elements with the same class.

The console displays an HTMLCollection containing the three paragraph elements.

The method does not return a regular array. Instead, it returns an HTMLCollection, which is an array-like collection of DOM elements.

Let’s understand how the code works:

  • Each paragraph has the class name message.
  • getElementsByClassName("message") selects all matching elements.
  • The selected elements are stored in the elements variable.
  • console.log(elements) displays the collection in the browser console.

Change Text Color Using getElementsByClassName()

You can use getElementsByClassName() to select multiple elements and modify their styles with a loop.

For example, you can change the text color of every paragraph that has the same class.

Web4Learners Example HTML
OUTPUT
Ready to run.

When you click the Change Color button, all three paragraphs turn blue.

The for loop iterates through the collection, and elements[i] accesses each paragraph individually.

The statement elements[i].style.color = "blue" changes the text color of the current element.

This approach is useful for updating multiple product names, notification messages, or other elements on a webpage.

Access Individual Elements Using getElementsByClassName()

Although getElementsByClassName() selects multiple elements, you can access each element individually using its index.

For example:

Web4Learners Example HTML
OUTPUT
Ready to run.

The first element has index 0, the second has index 1, and the third has index 2.

You can use the length property to find the number of elements in the collection.

const topics = document.getElementsByClassName("topic");

console.log(topics.length);

Output:

3

The length property returns the number of matching elements currently in the collection.

Remember that indexes start at zero, not one.

Select Elements with Multiple Class Names

The getElementsByClassName() method can also select elements that contain multiple specified classes.

Separate the class names with spaces inside the string.

<p class="message active">Active Message</p>
<p class="message">Normal Message</p>
<p class="message active">Another Active Message</p>

<script>
    const elements =
        document.getElementsByClassName("message active");

    console.log(elements.length);
</script>

Output:

2

The method selects elements that have both the message and active classes.

An element with only the message class does not match this selection.

Important: A space between class names means that the element must contain all the specified classes. It does not mean that the method searches for a descendant element.

What Is a Live HTMLCollection?

One important feature of getElementsByClassName() is that it returns a live HTMLCollection.

A live collection automatically reflects changes to the document that affect which elements match the specified class name.

Consider this example:

<p class="item">First Item</p>
<p class="item">Second Item</p>

<script>
    const items = document.getElementsByClassName("item");

    console.log(items.length);

    const newItem = document.createElement("p");
    newItem.className = "item";
    newItem.textContent = "Third Item";

    document.body.appendChild(newItem);

    console.log(items.length);
</script>

Output:

2
3

Initially, the collection contains two elements.

After JavaScript creates a third paragraph with the class item and adds it to the document, the collection automatically includes it.

The items variable does not need to be reassigned.

This behavior is useful, but it is important to remember when adding or removing classes while looping through a collection.

getElementsByClassName() vs getElementById()

Both methods are used to select HTML elements, but they work differently.

FeaturegetElementsByClassName()getElementById()
Selection methodClass nameID
Number of resultsZero or more elementsOne matching element or null
Return typeHTMLCollectionElement or null
Requires . or #NoNo
Can select multiple elementsYesNo
Live collectionYesNot applicable
Exampledocument.getElementsByClassName("item")document.getElementById("item")

Use getElementById() when selecting one uniquely identified element. Use getElementsByClassName() when selecting elements that share a class.

getElementsByClassName() vs querySelectorAll()

JavaScript also provides querySelectorAll(), which can select multiple elements using CSS selectors.

FeaturegetElementsByClassName()querySelectorAll()
Selector supportClass namesCSS selectors
Return typeLive HTMLCollectionStatic NodeList
Multiple elementsYesYes
Class selector examplegetElementsByClassName("item")querySelectorAll(".item")
Supports complex selectorsNoYes

For example, both statements can select elements with the item class:

const items1 = document.getElementsByClassName("item");

const items2 = document.querySelectorAll(".item");

The main difference is that the first returns a live collection, while the second returns a static collection that does not automatically update when the document changes.

Use getElementsByClassName() for direct class-based selection. Use querySelectorAll() when you need more flexible CSS selectors.

Common Mistakes When Using getElementsByClassName()

Adding a Dot Before the Class Name

Do not use a CSS dot when passing a class name to this method.

Incorrect:

document.getElementsByClassName(".message");

Correct:

document.getElementsByClassName("message");

Treating the Result as a Single Element

The method returns a collection, even when only one element matches.

Incorrect:

const elements = document.getElementsByClassName("message");

elements.style.color = "blue";

This does not work because the collection itself does not have the element’s style property.

Correct:

const elements = document.getElementsByClassName("message");

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

Forgetting That Indexes Start at Zero

Use elements[0] to access the first element, not elements[1].

Modifying a Live Collection While Iterating

If you remove a class from elements while looping through a live collection, the collection changes immediately. This can cause some elements to be skipped.

When necessary, convert the collection to an array before modifying the matching elements.

const items = Array.from(
    document.getElementsByClassName("item")
);

items.forEach(function (item) {
    item.classList.remove("item");
});

This creates an array snapshot so that removing classes does not change the array being iterated over.

Best Practices for Using getElementsByClassName()

Follow these practices when using this DOM method:

  • Use meaningful class names that describe the purpose of the elements.
  • Remember that the method returns an HTMLCollection, not a regular array.
  • Use a loop when you need to modify every matching element.
  • Check the collection’s length before accessing an element by index when a match is not guaranteed.
  • Remember that the collection updates automatically when matching elements change.
  • Use querySelectorAll() when you need more complex CSS selectors.
  • Convert the collection to an array when you need array methods such as map() or filter().

These practices help you write clearer and more reliable JavaScript code.

Frequently Asked Questions

What does getElementsByClassName() do in JavaScript?

It selects all elements in the specified scope that have the given class name and returns them in an HTMLCollection.

What is the syntax of getElementsByClassName()?

document.getElementsByClassName("className");

Replace className with the class you want to select.

Can getElementsByClassName() select multiple elements?

Yes. It returns a collection containing all matching elements, not just the first match.

What does getElementsByClassName() return if no elements match?

It returns an empty HTMLCollection. Its length property will be 0.

Is getElementsByClassName() case-sensitive?

Yes. Class names are matched using their exact case. For example, message and Message are different class names.

What is the difference between HTMLCollection and NodeList?

An HTMLCollection returned by getElementsByClassName() is live, meaning it reflects relevant changes to the document. The NodeList returned by querySelectorAll() is static, meaning it does not automatically update when matching elements are added or removed.

Can I use getElementsByClassName() with multiple classes?

Yes. Separate class names with spaces. The method selects elements containing all the specified classes.

Can I use forEach() directly on getElementsByClassName()?

No. HTMLCollection does not provide the standard array forEach() method. You can use a for loop or convert the collection into an array with Array.from().

Summary

The JavaScript getElementsByClassName() method selects HTML elements based on their class names and returns a live HTMLCollection.

It is useful for changing the styles of multiple elements, reading their content, accessing individual elements by index, and creating interactive webpages.

Understanding its syntax, return type, live collection behavior, and differences from getElementById() and querySelectorAll() will help you use DOM selection methods effectively in your JavaScript projects.