Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 700
Richard Morgan Avatar asked Jan 02 '26 02:01

Richard Morgan


1 Answers

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();
});
like image 117
Bala Abhinav Avatar answered Jan 03 '26 17:01

Bala Abhinav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!