Wednesday, August 7, 2013

How to count the number of li (list elements) inside ul (unordered list) using Javascript

Yesterday, I was trying to count the number of list elements inside an unordered list. I came up with the following code:


var ul = document.getElementById("myul");
var liNodes = [];
 
for (var i = 0; i < ul.childNodes.length; i++) {
 if (ul.childNodes[i].nodeName == "LI") {
  liNodes.push(ul.childNodes[i]);
 }
}

No comments:

Post a Comment