Reputation: 175
I can't access HTMLCollection Type When I use getElementsByClassName.
I wanna get the length but I can't get that
var documentHeader = parent.document.all['header'];
var motionClass = documentHeader.getElementsByClassName('motion');
this is a result of motionClass
HTMLCollection []
0: div.motion
length: 1
__proto__ : HTMLColletion
If I access length result is 0
How can I result This Issue?
Upvotes: 4
Views: 3384
Reputation: 15489
To give a more modern approach - use documentQuerySelectorAll()
to get the collection - this can then be iterated over to give each item - or can give the length of the collection.
let motions = document.querySelectorAll('.motion');
console.log(motions.length); // gives 5
console.log(motions[2].textContent); // gives "3" - the text content of that element
<div class='motion'>1</div>
<div class='motion'>2</div>
<div class='motion'>3</div>
<div class='motion'>4</div>
<div class='motion'>5</div>
Upvotes: 3
Reputation: 4768
NOTE: Here we execute the code safely when the DOM is ready. Ensure you are doing that.
document.addEventListener('DOMContentLoaded', function() {
let motionArray = document.getElementsByClassName('motion');
console.log(motionArray.length);
});
<div class='motion'>test</div>
<div class='motion'>test</div>
<div class='motion'>test</div>
<div class='motion'>test</div>
<div class='motion'>test</div>
<div class='motion'>test</div>
<div class='motion'>test</div>
Upvotes: 5