如何删除使用querySelectorAll获取的元素?

问题描述 投票:0回答:4

这似乎是一个可以快速回答的问题,但我找不到。也许我正在搜索错误的术语?请不要使用库,尽管我不需要跨浏览器后备,但我的目标是该项目的所有最新版本。

我得到了一些元素:

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

这是可行的,但是我现在如何删除这些元素?我是否必须循环遍历它们并执行

element.parentNode.removeChild(element);
的事情,或者是否缺少一个简单的函数?

javascript element selectors-api
4个回答
95
投票

由于

NodeList
已经支持
forEach
,你可以使用:

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>

参见 NodeList.prototype.forEach()Element.remove()

Internet Explorer 支持。 IE 不支持

forEach
上的
NodeList
,IE 也不支持
remove
对象上的
Element
方法。因此,如果您还希望在 IE 中运行上述代码,只需在 JavaScript 代码的开头添加以下几行,并使用 Node.removeChild 来删除元素(或者使用 Element.removeChild )。删除()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>


91
投票

是的,你几乎是对的。

.querySelectorAll
返回一个冻结的 NodeList。你需要迭代它并做事。

Array.prototype.forEach.call( element, function( node ) {
    node.parentNode.removeChild( node );
});

即使你只得到一个结果,你也需要通过索引来访问它,比如

elements[0].parentNode.removeChild(elements[0]);

如果您只想想要查询一个元素,请使用

.querySelector
代替。在那里,您只需获取节点引用,无需使用索引进行访问。


30
投票

使用 Array.fromChildNode.remove 更加简洁:

Array.from(document.querySelectorAll('.someselector')).forEach(el => el.remove());

好吧,刚刚看到 NodeList 是可迭代的,所以它可以做得更短:

document.querySelectorAll('.someselector').forEach(el => el.remove());

1
投票

我们可以使用remove()函数从querySelectorall()中删除元素。确保删除功能只能在现代浏览器中使用。

// Fetch the elements to remove
const elements = document.querySelectorAll('.class-name');

// Iterate through the elements and remove them
elements.forEach(element => {
  element.remove();
});

参考 - https://bbbootstrap.com/code/remove-elements-that-were-fetched-using-queryselectorall-10186399

© www.soinside.com 2019 - 2024. All rights reserved.