简体   繁体   English

为什么这只遍历HTMLCollection的奇数元素?

[英]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. 当使用for ... of循环遍历从DOMParser返回的HTMLCollection时,仅返回奇数元素。 I don't think this happens with NodeLists or HTMLCollections not created with DOMParser. 我不认为不是用DOMParser创建的NodeLists或HTMLCollections 不会发生这种情况。 It also doesn't happen if I convert the HTMLCollection to an array. 如果将HTMLCollection转换为数组,也不会发生。

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. 通过将元素追加到正文,您可以它们从doc变量所包含的文档中删除

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. 而且,由于HTMLCollection在定义上是“活动的”,这意味着它始终反映DOM的当前状态,因此您正在访问第一个元素,并将其删除(通过将其附加到正文中)。所有元素都向上移动一个位置,因此以前的第二个变成第一,以前的第三个变成第二,依此类推。 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. 那就是第二个位置,索引1- 当前占据该位置/索引的元素是前一个第三元素,该段落包含数字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. 第二个小提琴的不同之处在于,您正在循环[...doc.body.children] -这是一个数组,该数组创建为HTMLCollection开头的元素的静态 ,一次性快照。 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. 因此,它不是活的 ,因此当元素附加到身体上时元素不会从元素中消失,因此循环遍历了所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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