简体   繁体   中英

Why is this only iterating over odd elements of HTMLCollection?

When using a for...of loop to iterate over an HTMLCollection returned from DOMParser only the odd elements are returned. I don't think this happens with NodeLists or HTMLCollections not created with DOMParser. It also doesn't happen if I convert the HTMLCollection to an array.

Any idea why this is happening?

if (!HTMLCollection.prototype[Symbol.iterator]) {
    HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
}

let parser = new DOMParser();
let markup = '<p>Node 1</p><p>Node 2</p><p>Node 3</p><p>Node 4</p><p>Node 5</p>';
let doc = parser.parseFromString(markup, "text/html");
for (let element of doc.body.children) {
    document.body.appendChild(element);
}
for (let element of doc.body.children) {
    //document.body.appendChild(element);
    console.log(element);
}

Make this little adjustment to your code - and in console, you will see all five paragraph elements show up, in the right order.

By appending elements to the body, you are removing them from the document your doc variable contains.

And since the HTMLCollection is "live" by definition, meaning it always reflects the current state of the DOM, you are accessing the first element, and removing it (by appending it to body.) All elements move up by one position, so the formerly second becomes first, formerly third becomes second, and so on. Now your loop moves to the "next" element, or more precisely, to the next position in the list. That is position number two, index 1 - and the element currently occupying this position/index is the former third element, the paragraph containing the number 3.


What's different in your second fiddle, is that you are looping over [...doc.body.children] - that is an array created as a static , one-time snapshot of the elements contained in the HTMLCollection at the start. Therefor it is not live , and therefor the elements don't disappear from it when they are appended to the body, and so the loop goes over all of them.

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