Skip to content
Advertisement

How to remove elements that were fetched using querySelectorAll?

This seems like something that would have a quick answer, but I can’t find one. Maybe I’m searching the wrong terms? No libraries please, though I don’t need cross-browser fallbacks, I’m targeting all the latest versions on this project.

I’m getting some elements:

element = document.querySelectorAll(".someselector");

This is working, but how do I now delete these elements? Do I have to loop through them and do the element.parentNode.removeChild(element); thing, or is there a simple function I’m missing?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement