如何使用 getElementsByTagName() 查找所有嵌套元素?
我有以下 HTML:
<html>
<head><title>Title</title></head>
<body>
<div id='div2'>
<a href='#'>1</a>
<div id='div1'>
<a href='#'>2</a>
</div>
</div>
</body>
</html>
... 和以下 Javascript 代码,我正在通过 Greasemonkey: 运行这些代码:
var nodes = document.body.getElementsByTagName('a');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
node.parentNode.removeChild(node);
}
我希望它能够找到并删除所有 A 标签;相反,它找到第一个,但找不到第二个。据我所知,第二个 A 标签的嵌套方式有困难。
有人可以让我知道如何使用 getElementsByTagName 删除所有标签吗?如果可能的话,我宁愿不使用 XPath,这是有原因的。
I have the following HTML:
<html>
<head><title>Title</title></head>
<body>
<div id='div2'>
<a href='#'>1</a>
<div id='div1'>
<a href='#'>2</a>
</div>
</div>
</body>
</html>
... and the following Javascript code, which I'm running through Greasemonkey:
var nodes = document.body.getElementsByTagName('a');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
node.parentNode.removeChild(node);
}
I would expect it to find and remove all A tags; instead it finds the first, but not the second. As far as I can tell it's having difficulty with the way the second A tag is nested.
Could someone please let me know how to remove all the tags, using getElementsByTagName? There are reasons I'd prefer not to use XPath if at all possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
捕获长度并按相反顺序删除。这将消除副作用。
但更好的方法...
将此指令添加到您的标头中:
然后您的整个代码将变为:
Capture the length and remove in reverse order. This will eliminate side effects.
But a better way...
Add this directive to your header:
Then your whole code becomes:
按照 Vinay 的回答:
如果您实际上没有使用迭代器来执行任何操作,那么使用这样的 for 循环是很奇怪的。
Following Vinay's answer:
Since using a for loop like that is bizarre if you aren't actually using the iterator for anything.
您犯的错误是删除节点然后跳到下一个元素。删除第一个 (#0) 会导致第二个成为第一个。
The mistake you had was to delete the node then skip to the next element. Deleting the very first one (#0) causes the second become the 1st.
将代码更改为
nodes.length,每次删除子项时都会评估长度。
change your code to
nodes.length gets evaluated everytime you remove a child.