How To Remove All Elements Of A Certain Class In JavaScript

In this tutorial you will learn how to remove all elements with a certain class from the DOM using JavaScript.

The Scenario:

Consider a web page with multiple elements that have the same class, and you want to remove all of them with a single action. This scenario is common when you want to delete or hide specific content or elements based on user interactions or other dynamic factors.

JavaScript Code to Remove all Elements of a Certain Class

To remove all elements with a particular class in JavaScript, you can follow these steps:

  1. Use the document.querySelectorAll() method to select all elements with the specified class.
  2. Loop through the selected elements using the forEach() method and remove each element.

Let’s break down the process with an example:

// Get all elements with a specific class
const elementsToRemove = document.querySelectorAll('.your-class-name');

// Loop through the selected elements and remove each one
elementsToRemove.forEach(element => {
  element.remove();
});

Here’s what each part of the code does:

  • document.querySelectorAll('.your-class-name') selects all elements with the class name 'your-class-name'. Replace 'your-class-name' with the actual class name you want to target.
  • The selected elements are stored in a NodeList, which is a collection of DOM elements.
  • We use the forEach() method to iterate over the NodeList and remove each element using the remove() method.

Complete Example to Remove all Elements with Specific Class

Here’s a complete example that demonstrates how to remove elements with a specific class:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Remove Elements by Class</title>
  <style>
    .to-remove {
      color: red;
    }
  </style>
</head>
<body>
  <p class="to-remove">This paragraph will be removed.</p>
  <p class="to-remove">This paragraph will also be removed.</p>
  <p>This paragraph will stay.</p>

  <button onclick="removeElementsByClass()">Remove Elements</button>

  <script>
    function removeElementsByClass() {
      // Get all elements with the class 'to-remove'
      const elementsToRemove = document.querySelectorAll('.to-remove');

      // Loop through the selected elements and remove each one
      elementsToRemove.forEach(element => {
        element.remove();
      });
    }
  </script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy