How to get length of getElementsByTagName using javascript
Working with some sample code to sort a list inside a:
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); produces this:
a, console.log (b.length); leads to 0
How can I get the number of elements in b so that I can iterate over them to sort the shapes using figcaptions?
+3
source to share
2 answers
I agree with Bala's answer , mainly because I cannot reproduce your problem:
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>
0
source to share