views:

58

answers:

2

Hi All,

I need to count the amount of LI's in a top level UL.

My top level menu has 6 items in it but this could dynamically change. I thought this could work but it is still counting the child li's too :(

var numTopNavItems = 0;

$("ul.rmHorizontal > li").each(function (i) {

    numTopNavItems += i;
    alert("numTopNavItems = " + numTopNavItems);
});

Any ideas why this might be?

Thanks, James

+3  A: 

The proper way to count the number of matched element is

var numTopNavItems = $("ul.rmHorizontal > li").length;
alert("numTopNavItems = " + numTopNavItems);

The method should work as long as only the top level <ul> has class rmHorizontal. If not, try the selector

"ul.rmHorizontal:first > li"

instead.

KennyTM
+1  A: 

Got it thanks:

var count = $("#myList").children().length;
Sixfoot Studio
This will count all children of the `ul`, not just the `li`. Yes, the only things that *should* be direct children of an `ul` are `li` tags, but some pages may not honor this.
Piskvor
Thanks Piskvor, I have used the example below ;)
Sixfoot Studio