简体   繁体   English

HTML getElementsByClassName 返回长度为 0 的 HTMLCollection

[英]HTML getElementsByClassName returns HTMLCollection with length of 0

I am trying to use the js document.getElementsByClassName to locate an html element, which is actually the header of a table.我正在尝试使用js document.getElementsByClassName来定位一个 html 元素,它实际上是一个表的 header 元素。

For the following codes:对于以下代码:

console.log(document.getElementsByClassName('gtableheader'));

From the Firebug , I can see it log a HTMLCollection , and when I click it, it shows:Firebug ,我可以看到它记录了一个HTMLCollection ,当我单击它时,它显示:

-> 0         tr.gtableheader
   length    1

So it do locate the element I want.所以它确实找到了我想要的元素。

But when I using:但是当我使用:

console.log(document.getElementsByClassName('gtableheader').length);

Then output is 0 .然后 output 为0 That's so weird, any ideas about this?太奇怪了,有什么想法吗?

That's because the getElementsByClassName returns a live collection. 那是因为getElementsByClassName返回一个实时集合。 the length property of the object is 0 because at that point of time there is no element with that className in the DOM. 对象的length属性为0因为在那个时间点,DOM中没有带有该className的元素。 Since the console shows the live representation of an object, it shows all the matching elements when the elements are added to the DOM. 由于控制台显示对象的实时表示,因此当元素添加到DOM时,它会显示所有匹配的元素。

DOM parser parses the documents from top to bottom, when it reaches to a tag, it parses it and adds the DOM representation of it (an instance of HTMLElement interface) to the Document Object Model. DOM解析器从上到下解析文档,当它到达标记时,它会解析它并将它的DOM表示( HTMLElement接口的实例)添加到文档对象模型。 You should either move the script tag to the end of body tag or listen to DOMContentLoaded event which is fired when the initial HTML document has been completely loaded and parsed. 您应该将脚本标记移动到body标记的末尾,或者监听在完全加载和解析初始HTML文档时触发的DOMContentLoaded事件。

Using getElementsByClassName() will return all the elements with that class name in a document as a NodeList. 使用getElementsByClassName()将在文档中将具有该类名的所有元素作为NodeList返回。 This object represents a collection of nodes that can be accessed by index numbers, which starts in 0. In order to access the elements in the NodeList you will have to use a loop. 此对象表示可以通过索引号访问的节点集合,从0开始。要访问NodeList中的元素,您必须使用循环。

When you console.log(document.getElementsByClassName('gtableheader').length); 当你console.log(document.getElementsByClassName('gtableheader').length); you see 0 because when you run it there is no element with class gtableheader . 你看到0因为当你运行它时没有类gtableheader元素。 You are able to see the items in the console because document.getElementsByClassName() returns a live collection that is updated when the new elements are added. 您可以在控制台中查看项目,因为document.getElementsByClassName()返回在添加新元素时更新的实时集合。

As well, in the code you are using and the length is 0, you can use the code below to access the class name. 同样,在您使用的代码中,长度为0,您可以使用下面的代码访问类名。

document.getElementsByClassName('gtableheader')[0].style.color="red";

If you want to access all the elements in the class you can use a for loop. 如果要访问类中的所有元素,可以使用for循环。

var x = document.getElementsByClassName('gtableheader');
for (var i = 0; i < x.length; i++) {
    x[i].style.color = "red";
}

More information: http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp 更多信息: http//www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

Use this to make it work 用它来使它工作

window.addEventListener("load", function(event) {
    console.log(document.getElementsByClassName('gtableheader').length);
});

I had a similar problem, but the other answers here didn't lead to my solution. 我有类似的问题,但其他答案并没有导致我的解决方案。 I eventually realized that at the time my code was running, the DOM wasn't yet fully constructed, thus the empty array. 我最终意识到,在我的代码运行时,DOM尚未完全构造,因此是空数组。 What I was seeing in the console, a populated array, was what existed after the DOM was fully formed and the script was complete. 我在控制台中看到的是一个填充的数组,这是在DOM完全形成并且脚本完成之后存在的。

What worked for me was to wrap the code that needed the array within a MutationObserver and set it to watch the hard-coded div containing the sections that would be dynamically generated (see this StackOverflow answer and the MDN documentation ). 对我来说有用的是在MutationObserver中包含需要该数组的代码,并将其设置为观察包含将动态生成的部分的硬编码div(请参阅此StackOverflow答案MDN文档 )。

Try this: 试试这个:

var divArray = document.getElementById('hardCodedContainer');

var observer = new MutationObserver(function(){
   console.log(document.getElementsByClassName('gtableheader').length);
   console.log(document.getElementsByClassName('gtableheader'));
};

observer.observe(divArray, { attributes: false, childList: true, subtree: true });

// When you've got what you need, you should call this function to trigger a disconnect 
function classesFound(){
   observer.disconnect();
};

您只需要在声明类的html代码之后调用js文件。

I had this problem asking for the elements just after its dynamic creation, fixed with setTiemout()我有这个问题在动态创建之后要求元素,用 setTiemout() 修复

Simply place your <script> tag before </body>只需将<script>标签放在</body>之前

If <script> tag is not added at end of the <body> tag, DOM may not be ready by that time, thus preventing javascript to work on it, leading to unknown behaviors如果在<body>标签的末尾没有添加<script>标签,那么到那时 DOM 可能还没有准备好,从而阻止 javascript 对其进行处理,从而导致未知行为

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

相关问题 为什么 document.getElementsByName 返回一个 NodeList 而 document.getElementsByClassName 返回一个 HTMLCollection? - Why does document.getElementsByName return a NodeList while document.getElementsByClassName returns an HTMLCollection? HTMLCollection的长度为8,但记录其任何索引是否返回未定义? - HTMLCollection's length is 8 but logging any of its indices returns undefined? 即使使用 document.readyState || HTMLCollection 返回 0 作为长度在“DOMContentLoaded”之后 - HTMLCollection returns 0 as length even with document.readyState || after "DOMContentLoaded" 无法从getElementsByClassName访问HTMLCollection中的元素 - Unable to access elements in HTMLCollection from getElementsByClassName HTMLCollection的长度不起作用 - Length of an HTMLCollection not working HTMLcollection 0 列表长度,[n] 返回未定义,转换为数组返回空数组 - HTMLcollection 0 list length, [n] returns undefined, converting to an array returns an empty array getElementsByName返回节点列表或htmlcollection - getElementsByName returns nodelist or htmlcollection Javascript (HTMLCollection) 中的 object 长度不一致 - Inconsistent object length in Javascript (HTMLCollection) 无法获取getElementsByClassName的长度 - cannot get length of getElementsByClassName 从 getElementsByClassName 迭代 HTMLCollection 时的奇怪行为 - Strange behavior when iterating over HTMLCollection from getElementsByClassName
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM