Antonio Moore
Antonio Moore

Reputation: 940

JQuery: How to find out how many children an element has?

How can I use jQuery to find out how many children an element has?

Say I have the following structure:

<div id="container">
   <div id="column1">
      <div id="asset1"></div>
      <div id="asset2"></div>
   </div>
   <div id="column2">
      <div id="asset1"></div>
      <div id="asset2"></div>
   </div>
</div>

I want to find out how many children the div element: container, has. In this case it would return 2...

Upvotes: 8

Views: 8832

Answers (2)

Richard Dalton
Richard Dalton

Reputation: 35803

Use the direct children selector (>) and the length property:

$('#container > *').length

Example - http://jsfiddle.net/TtV8d/

Upvotes: 8

T.J. Crowder
T.J. Crowder

Reputation: 1075597

Use children and length:

$("#container").children().length

Upvotes: 21

Related Questions