admin管理员组文章数量:1434914
In an angular app I am using plain JS to get the elements by class name Code:
var testElements = document.getElementsByClassName("project-link");
console.log(testElements);
this prints as such:
[item: function, namedItem: function]
0: a.project-link.ng-binding
1: a.project-link.ng-binding
...
30: a.project-link.ng-binding
length: 32
__proto__: HTMLCollection
However. if I try printing an item alone, this returns null:
console.log(testElements.item(4));
null
I don't understand what is wrong with this code, I have also tried the Array.prototype.filter.call function and it doesn't work either. Any ideas?
In an angular app I am using plain JS to get the elements by class name Code:
var testElements = document.getElementsByClassName("project-link");
console.log(testElements);
this prints as such:
[item: function, namedItem: function]
0: a.project-link.ng-binding
1: a.project-link.ng-binding
...
30: a.project-link.ng-binding
length: 32
__proto__: HTMLCollection
However. if I try printing an item alone, this returns null:
console.log(testElements.item(4));
null
I don't understand what is wrong with this code, I have also tried the Array.prototype.filter.call function and it doesn't work either. Any ideas?
Share Improve this question asked Feb 18, 2015 at 12:38 Ioana GrozavIoana Grozav 1331 silver badge7 bronze badges 4- 1 Itsn't it an array? Shouldn't you be using testElements[] – paje007 Commented Feb 18, 2015 at 12:46
- It is an array, but I don't understand what you mean by saying I should be using testElements[] . if I console out something like testElements[3] I just get an undefined error – Ioana Grozav Commented Feb 18, 2015 at 13:14
- also, might be worth mentioning that when trying console.log(testElements.length); this turns out 0 – Ioana Grozav Commented Feb 18, 2015 at 13:17
- I e to the same problem as you did, and still no solutions...Do you think it might relate to lifecycle? – yuan Commented May 5, 2019 at 7:38
3 Answers
Reset to default 3I fixed this bug by adding my code inside the window load function:
window.addEventListener("load", function(event) {
// your code ....
});
this is because the JS code is loaded before the dom tree in the HTML is built. At this time, the page is still empty, so null is returned.
Use window.onload
<script >
window.onload = function() {
const testElement=document.getElementsByClassName("project-link").item(0);
console.log(testElement);
}
</script>
setTimeout(() => {
console.log(testElements.item(4));
}, 0);
Try this,
It might help~
I don't know why, but it works for me.
本文标签: javascriptHTMLCollectionitem() function returns nullStack Overflow
版权声明:本文标题:javascript - HTMLCollection.item() function returns null - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745619764a2666613.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论