Sixfoot Studio
Sixfoot Studio

Reputation: 3001

jquery count li's in top level UL

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

Upvotes: 2

Views: 4419

Answers (2)

Sixfoot Studio
Sixfoot Studio

Reputation: 3001

Got it thanks:

var count = $("#myList").children().length;

Upvotes: 1

kennytm
kennytm

Reputation: 523274

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.

Upvotes: 4

Related Questions