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:
but, console.log(b.length); results in 0
how can number of items in b can iterate through them sort figures figcaptions?
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
Post a Comment