How to remove elements that were fetched using querySelectorAll?

岁酱吖の 提交于 2019-11-29 23:32: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.

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().

Internet Explorer support. IE does not support forEach on NodeList hence if you also wish to make the above code work in IE, just add this piece of code at the beginning of your JavaScript code:

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

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

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!