How to remove elements that were fetched using que

2019-03-11 00:15发布

his 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");

YEY!

How do I delete these elements? What am I missing? Do I have to loop through them and do the element.parentNode.removeChild(element); thing, or is there a simple function I'm missing?

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-11 00:52

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.

查看更多
Evening l夕情丶
3楼-- · 2019-03-11 01:05

Since the NodeList already supports the forEach you can just use

document.querySelectorAll(".someselector").forEach(e => e.parentNode.removeChild(e));
<div>
  <span class="someselector">1</span>
  <span class="someselector">2</span>
  Should be empty
</div>

See the NodeList.prototype.forEach(). Just bear in mind that Internet Explorer is not supported.

Edit: Internet Explorer support. If you also wish to make the above code working in IE, just add this piece of code anywhere before in your JS:

if (!NodeList.prototype.forEach && Array.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

..and NodeList in IE will suddenly support forEach as well.

查看更多
时光不老,我们不散
4楼-- · 2019-03-11 01:05

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());
查看更多
登录 后发表回答