How to Remove All Elements Returned by JavaScript's querySelectorAll() Method?

Quick overview of how to remove all elements returned by querySelectorAll() in JavaScript

The querySelectorAll() method returns a static / non-live NodeList collection of elements when there's at least one match, and an empty NodeList if there are no matches. With that information, we can simply loop over the NodeList collection returned by querySelectorAll() and remove the DOM nodes linearly.

We can use the following loops to loop over the NodeList object (which is iterable because it is an "array-like object" — i.e. it has a length property and indexed elements):

  • for loop
  • for...of loop
  • forEach loop

Avoid using for...in loop to iterate over the items in a NodeList because they will also enumerate its length and item properties.

Looping Over NodeList and Using ChildNode.remove()

We can simply loop over the collection and use remove() to remove the element from the tree it belongs to.

Please note that the remove() method is not supported by any version of Internet Explorer. You can use Node.removeChild() instead, or use a polyfill.

For example:

const collection = document.querySelectorAll('p');

for (let i = 0; i < collection.length; i++) {
    collection[i].remove();
}
// ES6+
const collection = document.querySelectorAll('p');

for (const elem of collection) {
    elem.remove();
}
// ES5+
document.querySelectorAll('p').forEach(function (elem) {
    elem.remove();
});

// ES6+
document.querySelectorAll('p').forEach((elem) => elem.remove());

Looping Over NodeList and Using Node.removeChild()

Using Node.removeChild() has great browser support (new and old). It removes a child node from the DOM and returns the removed node.

With that information, we can simply loop over the collection and use parentNode.removeChild() to remove an element from the DOM like so:

const collection = document.querySelectorAll('p');

for (let i = 0; i < collection.length; i++) {
    const elem = collection[i];
    elem.parentNode.removeChild(elem);
}
// ES6+
const collection = document.querySelectorAll('p');

for (const elem of collection) {
    elem.parentNode.removeChild(elem);
}
// ES5+
document.querySelectorAll('p').forEach(function (elem) {
    elem.parentNode.removeChild(elem);
});

// ES6+
document.querySelectorAll('p').forEach((elem) => elem.parentNode.removeChild(elem));

Hope you found this post useful. It was published . Please show your love and support by sharing this post.