admin管理员组文章数量:1401799
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?
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?
Share Improve this question asked Dec 26, 2018 at 2:50 EddyKimEddyKim 1751 silver badge14 bronze badges 4-
7
Don't use
document.all
. – SLaks Commented Dec 26, 2018 at 2:52 - 2 You're probably accessing it after the element no longer exists / matches. – SLaks Commented Dec 26, 2018 at 2:52
- 2 Please show us all the relevant code including the CSS and HTML. And, be sure to show the location where you've embedded your script into the HTML. – Scott Marcus Commented Dec 26, 2018 at 3:04
- I found why was not working. iframe process before parent Document Loaded. I resolved Thank you. – EddyKim Commented Dec 26, 2018 at 6:30
2 Answers
Reset to default 5NOTE: 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>
本文标签: javascriptI can39t access HTMLCollectionStack Overflow
版权声明:本文标题:javascript - I can't access HTMLCollection - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744314362a2600188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论