Count immediate child div elements using jQuery

Dónal picture Dónal · Oct 30, 2008 · Viewed 288.2k times · Source

I have the following HTML node structure:

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz"></div>
  </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).

Answer

Garry Shutler picture Garry Shutler · Oct 30, 2008
$("#foo > div").length

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