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

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

Please note that typically, a forEach loop does not exist on an array-like object. However, NodeList object implements a NodeList.prototype.forEach() method, which is why it can be used on a NodeList object.

Avoid using for...in loop to iterate over the items in a NodeList because it 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));

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.