W3jar
214 words
1 minutes

How to Remove All Elements with a Specific Class Using JavaScript

To remove all elements with a specific class using JavaScript, you can use the document.querySelectorAll method to select all elements with that class and then iterate over the NodeList to remove each one. Here’s a step-by-step approach:

  1. Select All Elements with the Class: Use document.querySelectorAll to get a NodeList of all elements with the specified class.

  2. Iterate Over the NodeList: Use a loop to iterate over the NodeList and remove each element.

Here’s a simple example:

// Replace 'your-class-name' with the class you want to target
const elements = document.querySelectorAll(".your-class-name");

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

Explanation:#

  • document.querySelectorAll('.your-class-name'): This method returns a NodeList of all elements with the class your-class-name. Make sure to include the . before the class name to indicate it’s a class selector.

  • elements.forEach(element => { element.remove(); });: This loop goes through each element in the NodeList and removes it from the DOM using the .remove() method.

Notes:#

  • Browser Compatibility: The .remove() method is well-supported in modern browsers. If you need to support very old browsers, you might use a different approach like parentNode.removeChild(). For example:

    elements.forEach((element) => {
        element.parentNode.removeChild(element);
    });
    
  • Class Names with Multiple Classes: If you need to target elements with multiple classes, adjust the selector accordingly, e.g., .class1.class2.

This method is efficient and straightforward for removing elements based on their class names.