最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTMLCollection.item() function returns null - Stack Overflow

programmeradmin10浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 3

I 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.

发布评论

评论列表(0)

  1. 暂无评论