2017-07-28 5 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

私はfigcaptionsで私の人物を並べ替えることができますので、bの項目の数を得ることができますか? HTMLがロードされる前に、あなたのJavaScriptが実行を開始したときに

enter image description here

+1

'のdocument.getElementById( "timelineul")。length' ?? – marekful

+1

@marekful真剣に? – undefined

+0

問題は、 'getElementsByTagName()'があなたが次に操作している**ライブNodeList **を返しているのかどうか疑問に思っています。しかし、それは私が眠るのに6amと時間です。代わりに 'querySelector()'でリストを取得してみてください。 –

答えて

3

このような状況が発生します。その場合は、その後、あなたがそうのようなDomContentLoadedイベント内sortlistが()関数の呼び出しをラップする必要がある場合があります:

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>

関連する問題