JavaScript DOM: Getting Elements by Class Name

JavaScript DOM: Getting Elements by Class Name

In HTML, a class is a way to group elements together that share a common purpose or style. Unlike IDs, which must be unique, many elements on a page can share the same class name. This makes classes perfect for applying the same behavior or appearance to multiple elements at once — such as styling all buttons the same way, or showing several alerts when clicked.

In JavaScript, you can interact with elements that share the same class using document.getElementsByClassName(). This method lets you select all elements with a specific class name and work with them as a group. Whether you’re updating their text, changing their style, or making them respond to clicks, this method gives you control over many elements at once. Let’s dive in and explore how it works step by step, using fun, lively examples.

Basic Syntax of getElementsByClassName

The getElementsByClassName() method is a built-in JavaScript function that belongs to the document object. When you call it and pass a class name (as a string), it returns a live HTMLCollection of all elements that have that class. This collection is not an array, but you can still loop through it or access items by index.

Here’s a fun starting example using animals that share the class name “jungle”:

<!DOCTYPE html>
<html>
<head>
  <title>Animal Class Example</title>
</head>
<body>

  <div class="jungle">Lion</div>
  <div class="jungle">Tiger</div>
  <div class="jungle">Leopard</div>

  <script>

    const jungleAnimals = document.getElementsByClassName('jungle');
    console.log(jungleAnimals.length); // Output: 3
    console.log(jungleAnimals[0].textContent); // Output: Lion

  </script>

</body>
</html>

Here, JavaScript selects all elements with the class jungle and logs how many there are. It also prints the text of the first animal. This shows how easy it is to access multiple elements with the same class.

Accessing Multiple Elements with the Same Class

Since getElementsByClassName returns a collection, you can loop through all the elements using a for loop or for...of. Let’s use a fun example where several <p> tags have the class dog, and we want to update each one with a bark.

<!DOCTYPE html>
<html>
<head>
  <title>Dog Class Example</title>
</head>
<body>

  <p class="dog">Beagle</p>
  <p class="dog">Bulldog</p>
  <p class="dog">Labrador</p>

  <script>

    const dogs = document.getElementsByClassName('dog');

    for (let dog of dogs) {
      dog.textContent += " says Woof!";
    }

  </script>

</body>
</html>

Each paragraph with the class dog gets updated to include “says Woof!” right after its name. This is a simple way to apply the same change to every matching element.

Working with Individual Elements from a Class Collection

Sometimes, you may want to work with only one element from the group. Since the collection works like an array, you can use an index to access a specific item — like the first or the last.

Here’s an example using a group of birds. We’ll highlight just the first bird:

<!DOCTYPE html>
<html>
<head>
  <title>Bird Class Example</title>
</head>
<body>

  <div class="bird">Sparrow</div>
  <div class="bird">Parrot</div>
  <div class="bird">Eagle</div>

  <script>

    const birds = document.getElementsByClassName('bird');
    birds[0].style.fontWeight = 'bold';
    birds[0].style.color = 'green';

  </script>

</body>
</html>

Here, only the first bird in the list — the Sparrow — gets bold text and a green color. You can also target the last item using birds[birds.length - 1] if needed.

Changing Style of Elements by Class Name

You can use class names to change the style of several elements at once. This is especially useful when you want to highlight certain elements or give them a visual effect.

Let’s style all buttons related to movies using a shared class:

<!DOCTYPE html>
<html>
<head>
  <title>Movie Button Styling</title>
</head>
<body>

  <button class="movie">Inception</button>
  <button class="movie">Matrix</button>
  <button class="movie">Interstellar</button>

  <script>

    const movieButtons = document.getElementsByClassName('movie');

    for (let button of movieButtons) {
      button.style.cursor = 'pointer';
      button.style.backgroundColor = 'black';
      button.style.color = 'white';
      button.style.padding = '10px';
    }

  </script>
</body>
</html>

Every movie-themed button gets a bold new look with a black background and white text, just like a cinema night!

Changing Text Content of Elements by Class Name

Beyond styles, you can also change the actual content of elements. If multiple elements need to show new information, doing it by class name is the cleanest way.

Let’s give each programming language label a fun update:

<!DOCTYPE html>
<html>
<head>
  <title>Languages List</title>
</head>
<body>

  <div class="language">Python</div>
  <div class="language">JavaScript</div>
  <div class="language">Rust</div>

  <script>

    const langs = document.getElementsByClassName('language');

    for (let lang of langs) {
      lang.textContent = `I love ${lang.textContent}!`;
    }

  </script>

</body>
</html>

Here, each language now reads like a love note: “I love Python!”, “I love JavaScript!”, and so on. It’s a cheerful way to update multiple texts.

Using Class Name to Add Interactivity

You can even make multiple elements interactive by attaching event listeners to them using their class. This is a powerful way to create dynamic, engaging user experiences.

Let’s build a mini chessboard where every square can be clicked:

<!DOCTYPE html>
<html>
<head>
  <title>Chessboard Click</title>
</head>
<body>

  <div class="chess-square">A1</div>
  <div class="chess-square">A2</div>
  <div class="chess-square">A3</div>

  <script>

    const squares = document.getElementsByClassName('chess-square');

    for (let square of squares) {

      // Make each square look clickable, add spacing, and a border
      square.style.cursor = 'pointer';
      square.style.margin = '20px 0';
      square.style.border = '2px solid black';
      square.style.padding = '10px';
      square.style.width = '60px';
      square.style.textAlign = 'center';

      square.addEventListener('click', () => {
        alert(`${square.textContent} was clicked!`);
      });

    }

  </script>

</body>
</html>

Clicking any square pops up an alert with the square’s name. Each element becomes active with just a few lines of code.

Nesting and Scoping with getElementsByClassName

Sometimes, you only want to get elements within a certain container. You can do that by calling getElementsByClassName on a specific element instead of the whole document.

Let’s imagine we have two containers of animals, and we want to only get animals from one list:

<!DOCTYPE html>
<html>
<head>
  <title>Scoped Class Example</title>
</head>
<body>

  <div id="wild">
    <div class="card">Lion</div>
    <div class="card">Leopard</div>
  </div>

  <div id="domestic">
    <div class="card">Dog</div>
    <div class="card">Cat</div>
  </div>

  <script>

    // Get the parent element with ID 'wild'
    const wildSection = document.getElementById('wild');

    // From within the wild section, get all elements with the class 'card'
    const wildCards = wildSection.getElementsByClassName('card');

    // Loop through each card in the wild section
    for (let card of wildCards) {

      // Add a red border to highlight wild animals only
      card.style.border = '2px solid red';

    }

  </script>

</body>
</html>

Only the animals in the wild container get red borders. This shows how you can scope your class selection to a part of the page.

Conclusion

In this article, we explored how to use document.getElementsByClassName() to find and control multiple elements on a page. From updating a pack of dogs to clicking on chess squares, this method makes it easy to work with groups of elements that share a common class. You learned how to loop through class collections, change styles, update content, and even add interactivity — all by targeting class names.

If your webpage is a team of elements working together, getElementsByClassName() is how you bring them into action all at once.

References

If you’re curious to explore further or want to double-check what you’ve learned, these trusted documentation pages offer more detailed explanations and examples:

Scroll to Top