views:

33908

answers:

5

Hi,

I have the following HTML node structure:

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz">
  </div>
  <span><span>
</div>

How do I count the number of immediate children of "foo", that are of type "div". In the example above, the result should be two ("bar" and "baz").

Cheers, Don

+47  A: 
$("#foo > div").size()

Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.

Garry Shutler
I was just wondering on Friday how to count table columns with jQuery. I'll have to try a similar approach: `$('#table > th').size()`.
Jim Schubert
+2  A: 
$('#foo > div').size()
gizmo
+8  A: 
$("#foo > div")

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result

Darko Z
+1  A: 

It's not working for me :( None of them.

JQuery is working because animations are working fine. But it always returns null. (I've put it inside of the Ready(function) to make sure the code is loaded before I count them.

My code is

var n_numTabs = $("#superpics > div").size(); // Counts number of Tabs

and my html is

<div id="superpics">
<div class="superpic_cont" id="block1"></div>
<div class="superpic_cont" id="block2"></div>
<div class="superpic_cont" id="block3"></div>
</div>
sergio
same situation here
henrijs
+1  A: 
var n_numTabs $("#superpics div").size();

or

var n_numTabs $("#superpics div").length;


As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.

Andrew Perkins