Adding a CSS Class to Multiple DOM Elements Using JavaScript


Welcome to a comprehensive guide on adding a CSS class to multiple DOM elements in HTML using JavaScript. Let’s dive into different approaches with detailed explanations, multiple examples, and even a practice coding problem to test your understanding.


Example:

Following HTML code defines CSS classes, and Javascript code to add and remove those classes. This can be used to understand later techniques (where only Javascript code will be shown).

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Class Manipulation Demo</title>
  
  <!-- > > > < < < --->
  <style>
    .box {
      width: 100px;
      height: 100px;
      border: 2px solid #333;
      margin: 10px;
      display: inline-block;
      text-align: center;
      line-height: 100px;
    }

    .bg-yellow {
      background-color: yellow;
    }

    .remove-me {
      text-decoration: line-through;
    }
  </style>
</head>
<body>

  <!-- > > > Divs to which style is added or removed < < < --->
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>

  <!-- > > > Javascript Code < < < --->
  <script>
    // JavaScript code for adding a class
    const elementsToAddClass = document.querySelectorAll('.box');

    elementsToAddClass.forEach(element => {
      element.classList.add('bg-yellow');
    });

    // JavaScript code for removing a class
    const elementsToRemoveClass = document.querySelectorAll('.box');

    elementsToRemoveClass.forEach(element => {
      element.classList.remove('remove-me');
    });
  </script>

</body>
</html>

in above example:

  • The .box class is applied to three ` <div> ` elements, creating boxes with simple border and styling.
  • The .bg-yellow class is added to each box using JavaScript, giving them a yellow background.
  • The .remove-me class is removed from each box, eliminating the text-decoration: line-through style.

With that 1st example, putting in context HTML JS CSS together, lets see some more in Javascript to do this.

Using querySelectorAll and a Loop

The document.querySelectorAll method selects elements based on a CSS selector. We then use a for…of loop to iterate over the collection and add a class to each element.

JavaScript
const elements = document.querySelectorAll('.your-selector');

for (const element of elements) {
  element.classList.add('your-class');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(element);
}

This method is effective, but keep in mind that the selection may need refreshing if elements change dynamically.

Using getElementsByClassName

Another approach is using getElementsByClassName, which returns a live HTMLCollection.

JavaScript
const elements = document.getElementsByClassName('your-class');

for (const element of elements) {
  element.classList.add('new-class');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(element);
}

Unlike querySelectorAll, HTMLCollection stays updated with dynamic changes.


Using forEach with document.querySelectorAll

Combine forEach with document.querySelectorAll for a concise syntax. Just a loop variation.

JavaScript
document.querySelectorAll('.your-selector').forEach(element => {
  element.classList.add('your-class');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(element);
});

Using the Spread Operator

Convert NodeList or HTMLCollection into an array with the spread operator.

JavaScript
[...document.querySelectorAll('.your-selector')].forEach(element => {
  element.classList.add('your-class');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(element);
});

This provides flexibility, especially for additional array operations.


Using the classList Property

The classList property of an element provides direct methods for adding, removing, or toggling classes.

JavaScript
const elements = document.querySelectorAll('.your-selector');

elements.forEach(element => {
  element.classList.add('your-class');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(element);
});

The classList approach is concise and easy to read.

Adding Multiple Classes to Multiple Elements

Pass multiple classes to the add method for efficient class management.

JavaScript
const boxes = document.querySelectorAll('.box');

for (const box of boxes) {
  box.classList.add(
    'bg-yellow',
    'second-class',
    'third-class'
  );
  // πŸ‘‡οΈ Output: Element with added classes
  console.log(box);
}

Add Class to Elements with Multiple, Different Selectors

The querySelectorAll method accepts multiple selectors, allowing selection based on various criteria.

JavaScript
const boxes = document.querySelectorAll('.box1, .box2, .box3');

for (const box of boxes) {
  box.classList.add('bg-yellow', 'second-class', 'third-class');
  box.classList.remove('second-class', 'third-class');
  // πŸ‘‡οΈ Output: Element with added and removed classes
  console.log(box);
}

Add a Class to Multiple Elements using forEach()

Utilize the forEach method to enhance code readability.

JavaScript
const boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
  box.classList.add('bg-yellow');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(box);
});

Use Array.from to convert HTMLCollection to an array when using getElementsByClassName.

JavaScript
const boxes = Array.from(document.getElementsByClassName('box'));

boxes.forEach(box => {
  box.classList.add('bg-yellow');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(box);
});

Add a Class to Multiple Elements using forEach()

Utilize the forEach method to enhance code readability.

JavaScript
const boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
  box.classList.add('bg-yellow');
  // πŸ‘‡οΈ Output: Element with added class
  console.log(box);
});

πŸ§ͺPractice Coding Problem: Removing a Class from Multiple Elements

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Given an HTML document with multiple elements having a class, your task is to write JavaScript code that removes a specific class from all those elements.

HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Your Coding Challenge</title>

    <style>
      .remove-me {
        color: red;
        font-weight: bold;
      }
    </style>
  </head>

  <body>
    <div class="remove-me">Element 1</div>
    <div class="remove-me">Element 2</div>
    <div class="remove-me">Element 3</div>
    <div class="keep-me">Element 4</div>
    <div class="remove-me">Element 5</div>

    <script src="solution.js"></script>
  </body>
</html>

Your JavaScript Solution (in solution.js):
Write JavaScript code to remove the class remove-me from all elements that currently have this class.
Please attempt before seeing the Answer:
JavaScript
// Solution here
const elementsToRemoveClass = document.querySelectorAll('.remove-me');

elementsToRemoveClass.forEach(element => {
  element.classList.remove('remove-me');
});

// πŸ‘‡οΈ Verify that the class has been removed
console.log(document.querySelectorAll('.remove-me'));

Conclusion:

Adding / removing CSS classes is vital, whenever you need to make bulk changes to styling or behavior of multiple elements on your webpage. Whether it’s styling, interaction, or animation, manipulating classes is a possible solution.

Hopefully it will be useful. Keep refining your skills and Happy coding! πŸ˜ŠπŸš€

Scroll to Top