How to count LI elements from a list

Hi, I have the next list:

<ul id='myul'>
 <li>a</li>
 <li>b
  <ul>
   <li>b1</li>
   <li>b2</li>
   <li>b3</li>
  </ul>
 </li>
 <li>c</li>
 <li>d</li>
</ul>

I would like to know how can I count the LI elements from ‘myul’ ( just a,b,c,d )

But not count b1, b2 and b3, in this case the function should return 4

Thanks

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]);
	}
}

liNodes will contain the LI nodes.

Thank you!

Firefox, Safari and Opera supports document.evaluate which makes life easier since you can use XPath to get the nodes you want:

var ul = document.getElementById("myul");
var result = document.evaluate("li", ul, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

var nextLi;

while (nextLi = result.iterateNext()) {
	alert(nextLi.firstChild.data);
}

More elegant and powerful solution than above, but it does not work in IE…

:nono:

The IE way:


var myUL = document.getElementById("myUL");
var list = myUL.children.tags("LI");
alert(list.length);