简体   繁体   English

遍历HTMLCollection

[英]iterating over HTMLCollection

I have an HTMLCollection containing all HTML nodes that use the script tag. 我有一个HTMLCollection,其中包含所有使用script标签的HTML节点。 I collect them by const scriptNodes = document.getElementsByTagName('script'); 我通过const scriptNodes = document.getElementsByTagName('script');收集它们 .

If I log the whole collection in Chrome dev tools, its length is 10 . 如果我将整个集合记录在Chrome开发工具中,则长度为10 If I unfold the collection and see its properties, I can see more than 10. I can even see a property called length , which is 12. This means that there are 2 properties not accessible. 如果我展开集合并查看其属性,则可以看到超过10个。甚至可以看到一个名为length的属性,即12。这意味着有2个属性不可访问。

I try to access to scriptNodes[10], scriptNodes[11] and they are undefined. 我尝试访问scriptNodes[10], scriptNodes[11] ,但它们未定义。 Even the API HTMLCollection.nodeItem(index) returns undefined, which they are not, I can see the content of those 'extra' properties. 甚至API HTMLCollection.nodeItem(index)返回undefined,但它们不是,我可以看到那些“额外”属性的内容。

I have tried for..of, for..in and those are not logged. 我尝试了for..of, for..in ,但未记录这些。

How am I supposed to access those extra/undefined properties? 我应该如何访问这些额外的/未定义的属性? Is that something related to Enumerability? 这与可枚举性有关吗?

Thanks! 谢谢!

A number of browser extensions can add script tags to your page. 许多浏览器扩展程序都可以将脚本标签添加到您的页面。 I am guessing that is why those extra script tags are showing up. 我猜这就是为什么这些额外的脚本标签出现的原因。 Possibly you are accessing the script tags at a point in time before the extra ones are loaded. 可能是在加载额外的脚本标记之前的某个时间点访问脚本标记。 If you place your code inside a setTimeout, you would likely get all of the script nodes. 如果将代码放在setTimeout中,则可能会获得所有脚本节点。 Try it and let us know if that is it. 试试看,让我们知道是否就是这样。

$(document).ready(function () {
    setTimeout(function () {
        var scriptNodes = document.getElementsByTagName('script');
        console.log('scriptNodes', scriptNodes);
    }, 2000); // or an even longer delay if you like
});

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

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