2017-07-28 28 views
3

通過一些示例代碼工作進行排序內的列表:如何獲得的getElementsByTagName的長度與JavaScript

function sortList() { 
    var list, i, switching, b, shouldSwitch; 
    list = document.getElementById("timelineul"); 
    switching = true; 
    /*Make a loop that will continue until 
    no switching has been done:*/ 
    while (switching) { 
    //start by saying: no switching is done: 
    switching = false; 
    b = list.getElementsByTagName("figcaption"); 
    //Loop through all list items: 
    console.log(b); 
    console.log(b.length); 
    for (i = 0; i < (b.length - 1); i++) { 
     //start by saying there should be no switching: 
     shouldSwitch = false; 
     /*check if the next item should 
     switch place with the current item:*/ 
     console.log(b[i].innerHTML); 
     console.log(b[i+1].innerHTML); 
     if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) { 
     /*if next item is alphabetically lower than current item, 
     mark as a switch and break the loop:*/ 
     shouldSwitch= true; 
     break; 
     } 
    } 
    if (shouldSwitch) { 
     /*If a switch has been marked, make the switch 
     and mark the switch as done:*/ 
     b[i].parentNode.insertBefore(b[i + 1], b[i]); 
     switching = true; 
    } 
    } 
} 

的console.log(B);產生這樣的:

enter image description here

但是, 的console.log(b.length個);結果爲0

如何獲取b中的項目數量,以便我可以遍歷它們以按照圖形對我的數字進行排序?

enter image description here

+1

'的document.getElementById( 「timelineul」)。length' ?? – marekful

+1

@marekful認真嗎? – undefined

+0

我想知道如果問題可能是由於'getElementsByTagName()'返回一個**活的NodeList **,你正在操縱,但它是早上6點和我睡覺(yup)的時間。嘗試使用'querySelector()'來獲取列表。 –

回答

3

這種情況時,加載HTML之前,你的JavaScript開始執行情況。如果是這樣的話,那麼你可能需要調用換到sortlist中的()函數,就像這樣DomContentLoaded事件中:

document.addEventListener("DOMContentLoaded", function(e) { 
    sortList(); 
}); 
+0

我試着用這個替換掉了這個調用,但是現在它從不調用sortList函數。它應該去哪裏? –

0

我同意Bala's answer,主要是因爲我無法重現您的問題:

var div = document.getElementById('a'); 
 
var spans = div.getElementsByTagName('span'); 
 

 
console.log(spans.length);
<div id="a"> 
 
    <ul> 
 
    <li><span>hi</span></li> 
 
    <li><span>yo</span></li> 
 
    <li><span>dude</span></li> 
 
    </ul> 
 
</div>