簡體   English   中英

我無法訪問 HTMLCollection

[英]I can't access HTMLCollection

當我使用 getElementsByClassName 時,我無法訪問 HTMLCollection 類型。

我想得到長度,但我不能得到那個

var documentHeader = parent.document.all['header'];
var motionClass = documentHeader.getElementsByClassName('motion');

這是motionClass的結果

HTMLCollection []
 0: div.motion
 length: 1
 __proto__ : HTMLColletion

如果我訪問長度結果為 0

我怎樣才能導致這個問題?

注意:這里我們在 DOM 准備好時安全地執行代碼。 確保你這樣做。

 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>

為了提供更現代的方法 - 使用documentQuerySelectorAll()獲取集合 - 然后可以迭代它以提供每個項目 - 或者可以提供集合的長度。

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM