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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745619764a4636448.html
评论列表(0条)