简体   繁体   中英

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.

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) .

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. NodeList objects are "live", which means that they change as you change the DOM. That is, tds.length is decrementing, but your i is incrementing as well - thus you're missing an element each iteration. If you turn it into an array first, as above, then your code should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM