简体   繁体   中英

I can't access HTMLCollection

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?

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM