[英]Why can't I iterate over all the elements returned by getElementsByTagName?
I am trying to replace a group of tags with another tag, but for some reason I can't seem to loop over all the tags that getElementsByTagName() returns. 我试图用另一个标签替换一组标签,但是由于某种原因,我似乎无法遍历getElementsByTagName()返回的所有标签。
In the example the second td
in the first row is skipped for some reason even though it shows up in the console.log(tds)
. 在此示例中 ,尽管第一行中的第二个td
出现在console.log(tds)
中,但由于某种原因还是被跳过了。
What is wrong with my code? 我的代码有什么问题?
Change the first line to: 将第一行更改为:
var tds = [].slice.call(document.getElementsByTagName('td'), 0);
The value returned from .getElementsByTagName()
is a NodeList, not an array. 从.getElementsByTagName()
返回的值是NodeList,而不是数组。 NodeList objects are "live", which means that they change as you change the DOM. NodeList对象是“活动的”,这意味着它们在您更改DOM时也会更改。 That is, tds.length
is decrementing, but your i
is incrementing as well - thus you're missing an element each iteration. 也就是说, tds.length
正在递减,但是您的i
也在递增-因此,每次迭代都缺少一个元素。 If you turn it into an array first, as above, then your code should work. 如果您如上所述首先将其转换为数组,则您的代码应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.