と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);これは、生成:
しかし、 にconsole.log(てb.length)。結果は0
私はfigcaptionsで私の人物を並べ替えることができますので、bの項目の数を得ることができますか? HTMLがロードされる前に、あなたのJavaScriptが実行を開始したときに
'のdocument.getElementById( "timelineul")。length' ?? – marekful
@marekful真剣に? – undefined
問題は、 'getElementsByTagName()'があなたが次に操作している**ライブNodeList **を返しているのかどうか疑問に思っています。しかし、それは私が眠るのに6amと時間です。代わりに 'querySelector()'でリストを取得してみてください。 –