How to remove elements that were fetched using querySelectorAll?
Yes, you're almost right. .querySelectorAll
returns a frozen NodeList. You need to iterate it and do things.
Array.prototype.forEach.call( element, function( node ) {
node.parentNode.removeChild( node );
});
Even if you only got one result, you would need to access it via index, like
elements[0].parentNode.removeChild(elements[0]);
If you only want to query for one element, use .querySelector
instead. There you just get the node reference without the need to access with an index.
Since the NodeList
already supports the forEach
you can just use:
document.querySelectorAll(".someselector").forEach(e => e.remove());
<div>
<span class="someselector">element 1</span>
<span class="someselector">element 2</span>
there shouldn't be any of the above "element" spans after you run the code
</div>
See the NodeList.prototype.forEach() and Element.remove()
Internet Explorer support. IE does not support the forEach
on the NodeList
and IE also doesn't support remove
method on Element
objects. Hence, if you also wish to run the above code in the IE, just add the following lines at the beginning of your JavaScript code, and to remove an element use the Node.removeChild instead (or use the Element.remove() polyfill):
if (!NodeList.prototype.forEach && Array.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
// ..then continue as usual with the forEach
document.querySelectorAll(".someselector").forEach(e => e.parentNode.removeChild(e));
<div>
<span class="someselector">element 1</span>
<span class="someselector">element 2</span>
Should be empty
</div>
Even more concise with Array.from and ChildNode.remove:
Array.from(document.querySelectorAll('.someselector')).forEach(el => el.remove());
Ok, just saw NodeList is iterable so it can be done even shorter:
document.querySelectorAll('.someselector').forEach(el => el.remove());