如何删除使用querySelectorAll获取的元素? [英] How to remove elements that were fetched using querySelectorAll?

查看:607
本文介绍了如何删除使用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.

我收到一些元素:

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

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

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?

推荐答案

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

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]);






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


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.

这篇关于如何删除使用querySelectorAll获取的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆