return elements that match specified CSS selector(s)

What is the best way to remove multiple elements using querySelectorAll()?

Answers:

  • To remove multiple elements selected with querySelectorAll(), you can follow these steps:

    1. Use querySelectorAll() to select the elements you want to remove.
    2. Convert the NodeList returned by querySelectorAll() into an array to use array methods.
    3. Iterate through the array and remove each element from the DOM.

    Here's an example of how to implement these steps in JavaScript:

    // Select multiple elements using querySelectorAll
    const elements = document.querySelectorAll('.class-to-remove');
    
    // Convert NodeList to Array and iterate through the elements
    elements.forEach(element => {
        element.remove(); // Remove each element from the DOM
    });
    

    Key Points

    • querySelectorAll returns a NodeList, which is not an array. However, it can be easily iterated using forEach.
    • The remove() method can be called directly on a DOM element to remove it from the document.
    • If you're targeting a large number of elements and performance is a concern, consider using documentFragment for batching the removals or using a different approach to minimize reflows/repaints.

    Alternative Option

    If you prefer a more functional approach without converting to an array, you can use forEach directly on the NodeList:

    // Using forEach directly on the NodeList
    elements.forEach(element => element.remove());
    

    This method works in modern browsers that support NodeList.prototype.forEach(). If you need to support older browsers, you would need to convert it to an array first.