tags:

views:

126

answers:

4

Hi,

I'm trying to count the number of child elements a certain category has.

This is the situation:

<ul id="select_cat">
  <li id="_1">Category 1 (<span>#</span>)</li>
  <li id="_2">Category 2 (<span>#</span>)</li>
</ul>

<ul id="cat_1>
  <li>Link 1</li>
  <li>Link 2</li>
  <li>Link 3</li>
</ul>

<ul id="cat_2">
  <li>Link 1</li>
  <li>Link 2</li>
</ul> 

So I want to count the number of children a category has. In this example the first cardinal sign should be 3, and the second should be 2.

How can I do this, using jQuery.

Check an example (not jQuery)

Thanks!

+1  A: 

Example:

$("#cat_2").children("li").length

I have a feeling the question wants to ask something more. Anyway, it's just wiring it up to some heuristic. E.g. iterate over the "select_cat" elements with each and use their ID/position/name to count the elements in a category above and then use a text on the span (isolated with find/child), etc.

My two cents: I'd make the server do it.

pst
+1 for being quicker :)
Sarfraz
Thanks for the quick response, but that's not what I'm looking for.With your solution, I'll have to add a line of code each time I add a category.There should be a way to count the children of every category,but I'm not sure how to accomplish this..Probably with a while loop, to count the number of <ul>'s with an ID cat_X..
Filip Breckx
Yep, something like that is exactly what I need, just don't know how to do this. Could you give me a hand please? I never was any good with loops. A shame, I know..
Filip Breckx
A: 

You can do either of this:

alert($("#cat_1").children("li").length);
alert($("#cat_1").children("li").size());
Sarfraz
+1  A: 
$('#select_cat li').each(function() {
 $('span', this).text($('#cat' + this.id).children().length);
});
Mathias Bynens
A: 
  $("#select_cat li").each(function(){
    $("span", this).html(
      $("#cat" + $(this).attr('id')).children().size();
    );
  });
Senne
So you're saying that this.id is less efficient than $(this).attr('id') ?
Senne
FYI, it’s more efficient to (1) just use `this.id` instead of `$(this).attr('id')`, (2) set `.text()` instead of `.html()`, and (3) read `.length` instead of calling the `.size()` method (resulting in an extra function call).
Mathias Bynens