return elements that match specified CSS selector(s)

How can I remove multiple elements using querySelectorAll()?

Answers:

  • To remove multiple elements using querySelectorAll() in JavaScript, you'll first select the elements you want to remove, iterate over the resulting NodeList, and then remove each element from the DOM. Here's a step-by-step guide:

    1. Use document.querySelectorAll() to select the elements you wish to remove.
    2. Convert the NodeList to an array (optional, but often useful for using array methods).
    3. Iterate over the array of elements and remove each one from its parent.

    Here’s an example:

    // Select all elements you want to remove
    const elementsToRemove = document.querySelectorAll('.class-to-remove'); 
    
    // Convert NodeList to an array to use forEach (optional)
    elementsToRemove.forEach(element => {
        element.parentNode.removeChild(element); // Remove each element from its parent
    });
    

    Explanation:

    • querySelectorAll('.class-to-remove') selects all elements with the specified class (you can modify the selector as needed).
    • The forEach method is called on the NodeList (or you could also use a simple for loop if preferred).
    • Each element is removed from its parent using removeChild().

    Alternative method:

    You can also use element.remove() directly on each element, which is more straightforward and doesn't require accessing the parent:

    const elementsToRemove = document.querySelectorAll('.class-to-remove'); 
    
    elementsToRemove.forEach(element => {
        element.remove(); // Directly removes the element from the DOM
    });
    

    Using element.remove() is generally cleaner and easier to read.

    Note:

    Keep in mind that if you're manipulating the DOM in a way that changes the structure while iterating (e.g., adding or removing elements), ensure your logic correctly accounts for that. However, since querySelectorAll retrieves a static NodeList at the time of the selection, issues typically arise when trying to modify the list being iterated over.