Table of Contents

The JavaScript getElementsByClassName() method selects HTML elements by their class name. It is useful when you want to work with several elements that share a CSS class, such as highlighting multiple paragraphs, updating a group of cards, or responding to changes in a set of page elements. In this tutorial, you will learn its syntax, return value, practical examples, and how it differs from other DOM selection methods.

What Is getElementsByClassName() in JavaScript?

getElementsByClassName() is a DOM method available on the Document and Element interfaces. It finds elements whose class list contains the specified class name and returns a live HTMLCollection of matching elements.

For example, if several HTML elements have the class highlight, you can select all of them with document.getElementsByClassName("highlight"). You can then loop through the collection to update their content or styles.

Syntax of getElementsByClassName()

document.getElementsByClassName(classNames);

Parameter: classNames is a string containing one or more class names separated by spaces. Do not include the dot (.) used in CSS class selectors.

Return value: A live HTMLCollection containing matching elements in tree order. If no elements match, the collection is empty and its length is zero.

1. Select Elements by a Single Class Name

Suppose a page contains several elements with the class message. You can select all of them and check how many elements were found.

<p class="message">Welcome to JavaScript</p>
<p class="message">Learn DOM methods</p>
<div class="message">Practice every day</div>

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

  console.log(messages.length); // 3
  console.log(messages[0].textContent);
</script>

The result is an HTMLCollection. You can access an item using its index, such as messages[0], and use the length property to get the number of matching elements.

2. Change the Content of Multiple Elements

You can use a loop to update the text of every element in the collection. The following example changes the content of all elements with the class notice.

<p class="notice">Old notice one</p>
<p class="notice">Old notice two</p>
<p class="notice">Old notice three</p>

<script>
  const notices = document.getElementsByClassName("notice");

  for (let i = 0; i < notices.length; i++) {
    notices[i].textContent = "This notice has been updated.";
  }
</script>

After the script runs, all three matching elements display the new text. Use textContent when inserting plain text rather than parsing a string as HTML.

3. Change the CSS Style of Selected Elements

The method is also useful for applying the same style to multiple elements. This example changes the background color and text color of every element with the class card.

<div class="card">First Card</div>
<div class="card">Second Card</div>
<div class="card">Third Card</div>

<script>
  const cards = document.getElementsByClassName("card");

  for (const card of cards) {
    card.style.backgroundColor = "lightblue";
    card.style.color = "black";
    card.style.padding = "12px";
  }
</script>

Every matching card receives the specified inline styles. For reusable styling, consider defining a CSS class and adding or removing it with classList.

4. Select Elements with Multiple Class Names

You can pass multiple class names separated by spaces. The returned collection includes only elements that contain all the specified classes. The order of the class names in the argument does not matter.

<div class="box active">Active box</div>
<div class="box">Normal box</div>
<div class="active box">Another active box</div>

<script>
  const activeBoxes =
    document.getElementsByClassName("box active");

  console.log(activeBoxes.length); // 2
</script>

The first and third elements contain both box and active, so they are included. The second element has only the box class and is excluded.

5. Select Elements Inside a Specific Parent

You do not have to search the entire document. You can call getElementsByClassName() on a parent element to find matching descendants only within that element.

<div id="content">
  <p class="item">First item inside</p>
  <p class="item">Second item inside</p>
</div>

<p class="item">Item outside the container</p>

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

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

Only descendants of the element with the ID content are included. The paragraph outside the container is not part of the collection.

6. Loop Through an HTMLCollection

The returned HTMLCollection supports indexed access and iteration. You can use a traditional for loop or a for...of loop to process its elements.

const products = document.getElementsByClassName("product");

// Traditional for loop
for (let i = 0; i < products.length; i++) {
  console.log(products[i].textContent);
}

// for...of loop
for (const product of products) {
  console.log(product.textContent);
}

An HTMLCollection is not an Array. Methods such as map() and filter() are not directly available on it. Convert the collection to an Array if you need those methods.

7. Convert HTMLCollection to an Array

You can use Array.from() or the spread syntax to create an Array from the HTMLCollection. The Array contains a snapshot of the elements at the time of conversion.

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

// Convert to an Array
const itemArray = Array.from(items);

// Use the map() method
const itemTexts = itemArray.map((item) => item.textContent);

console.log(itemTexts);

You can also use spread syntax:

const itemArray = [...document.getElementsByClassName("item")];

8. Understand the Live HTMLCollection

The HTMLCollection returned by getElementsByClassName() is live. It automatically reflects matching elements added to or removed from the document after the collection is created.

<p class="note">First note</p>

<script>
  const notes = document.getElementsByClassName("note");

  console.log(notes.length); // 1

  const newNote = document.createElement("p");
  newNote.className = "note";
  newNote.textContent = "Second note";
  document.body.appendChild(newNote);

  console.log(notes.length); // 2
</script>

The original collection now contains two elements even though the method was called only once. This live behavior can be useful, but it also means the collection can change while your code is running.

If you plan to remove or rearrange matching elements while looping, consider converting the collection to an Array first. That gives your loop a stable snapshot.

9. getElementsByClassName() vs. querySelectorAll()

Both methods can select elements by class, but they use different selection syntax and return different collection types.

// Live HTMLCollection; class name without a dot
const liveItems = document.getElementsByClassName("item");

// Static NodeList; CSS class selector includes a dot
const staticItems = document.querySelectorAll(".item");

getElementsByClassName() accepts class names and returns a live HTMLCollection. querySelectorAll() accepts any valid CSS selector and returns a static NodeList. For example, querySelectorAll(".card.active") can select elements that have both classes.

10. Common Mistakes and Best Practices

  • Including a dot before the class name: Use "active", not ".active". The dot belongs to CSS selector syntax used by methods such as querySelectorAll().
  • Expecting a single element: The method returns an HTMLCollection, even if only one element matches. Use an index and check the collection length when needed.
  • Assuming the result is an Array: Convert it with Array.from() before using Array-only methods such as map() or filter().
  • Forgetting multiple-class matching: When you pass multiple class names, an element must contain all of them to match.
  • Ignoring live collection behavior: Adding or removing matching elements changes the collection. Make an Array copy when you need a stable list.
  • Searching the wrong scope: Calling the method on document searches the document; calling it on an element searches its descendants.
  • Running code before the HTML is available: Place the script after the relevant markup or wait for the DOMContentLoaded event.

Categorized in:

Javascript, Js DOM,