Javascript HTML getElementsByClassName 返回长度为 0 的 HTMLCollection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33680420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML getElementsByClassName returns HTMLCollection with length of 0
提问by chrisTina
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 元素,它实际上是一个表的标题。
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
. That's so weird, any ideas about this?
然后输出是0
。这太奇怪了,有什么想法吗?
采纳答案by Victor Luna
Using getElementsByClassName()
will return all the elements with that class name in a document as a 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.
UsinggetElementsByClassName()
将返回文档中具有该类名的所有元素作为 NodeList。该对象表示可以通过索引号访问的节点集合,从 0 开始。为了访问 NodeList 中的元素,您必须使用循环。
When you console.log(document.getElementsByClassName('gtableheader').length);
you see 0 because when you run it there is no element with class 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.
当您console.log(document.getElementsByClassName('gtableheader').length);
看到 0 时,因为当您运行它时,没有带有 class 的元素gtableheader
。您可以在控制台中看到这些项目,因为它会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
回答by undefined
That's because the getElementsByClassName
returns a livecollection. the length
property of the object is 0
because at that point of time there is no element with that className in the DOM. Since the console shows the live representation of an object, it shows all the matching elements when the elements are added to the DOM.
那是因为getElementsByClassName
返回一个实时集合。length
对象的属性是0
因为在那个时间点,DOM 中没有具有该 className 的元素。由于控制台显示对象的实时表示,因此当元素添加到 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. 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.
DOM 解析器从上到下解析文档,当它到达一个标签时,它会解析它并将它的 DOM 表示(HTMLElement
接口的实例)添加到文档对象模型中。您应该将脚本标签移动到标签的末尾,body
或者监听DOMContentLoaded
在初始 HTML 文档完全加载和解析后触发的事件。
回答by Victor Luna
Use this to make it work
使用它来使它工作
window.addEventListener("load", function(event) {
console.log(document.getElementsByClassName('gtableheader').length);
});
回答by jamesthe500
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. 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 尚未完全构建,因此是空数组。我在控制台中看到的,一个填充的数组,是在 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 answerand 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();
};
回答by zdig
You just need to call the js file after the html code where the classes are declared.
您只需要在声明类的 html 代码之后调用 js 文件。