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

javascript - I can't access HTMLCollection - Stack Overflow

programmeradmin5浏览0评论

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

2 Answers 2

Reset to default 5

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>

发布评论

评论列表(0)

  1. 暂无评论