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:

enter image description here

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?

enter image description here

+3


source to share


2 answers


This situation occurs when your javascript starts executing before the html is loaded. If so, then you may need to include the call to sortList () in the DomContentLoaded event, for example:



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

      

+3


source


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>
      

Run codeHide result


0


source







All Articles