html - How to get length of getElementsByTagName with javascript -


working through example code sort list of within :

function sortlist() {   var list, i, switching, b, shouldswitch;   list = document.getelementbyid("timelineul");   switching = true;   /*make loop continue until   no switching has been done:*/   while (switching) {     //start saying: no switching done:     switching = false;     b = list.getelementsbytagname("figcaption");     //loop through list items:     console.log(b);     console.log(b.length);     (i = 0; < (b.length - 1); i++) {       //start saying there should no switching:       shouldswitch = false;       /*check if next item should       switch place 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 alphabetically lower current item,         mark switch , break loop:*/         shouldswitch= true;         break;       }     }     if (shouldswitch) {       /*if switch has been marked, make switch       , mark switch 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 number of items in b can iterate through them sort figures figcaptions?

enter image description here

this situation happens when javascript starts executing before html loaded. if case, might have wrap call sortlist() function within domcontentloaded event :

document.addeventlistener("domcontentloaded", function(e) {     sortlist(); }); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -