Richard Morgan
Richard Morgan

Reputation: 853

How to get length of getElementsByTagName with javascript

Working through some example code to sort a list of within 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:

enter image description here

but, console.log(b.length); results in 0

How can I get the number of items in b so I can iterate through them to sort my figures by figcaptions?

enter image description here

Upvotes: 3

Views: 804

Answers (2)

flygaio
flygaio

Reputation: 121

I agree with Bala's answer, mostly because I am unable to reproduce your issue:

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>

Upvotes: 0

Bala Abhinav
Bala Abhinav

Reputation: 1348

This situation happens when your javascript starts executing before the html is loaded. If that is the case, then you might have to wrap the call to the sortList() function within a DomContentLoaded event like so :

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

Upvotes: 3

Related Questions