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

新手上路,请多包涵

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

我得到一些元素:

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

这是有效的,但我现在如何删除这些元素?我是否必须遍历它们并执行 element.parentNode.removeChild(element); 事情,还是我缺少一个简单的功能?

原文由 Randy Hall 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

是的,你几乎是对的。 .querySelectorAll 返回 冻结的 NodeList 。你需要迭代它并做一些事情。

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

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

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


如果 只想 查询一个元素,请改用 .querySelector 。在那里,您只需获取 _节点引用_,而无需使用索引进行访问。

原文由 jAndy 发布,翻译遵循 CC BY-SA 3.0 许可协议

由于 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 remove NodeList Element 因此,如果您还希望在 IE 中运行上述代码,只需在 JavaScript 代码的开头添加以下行,并使用 Node.removeChild 代替删除元素(或 使用 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>

原文由 Ivan Sivak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题