views:

123

answers:

3

Is it possible using jQuery to count the number of div elements?

I have this code:

<div id = "center">
  <div class ="name">text text</div>
  <div class ="name">text text text ... </div>
  <div class ="name">text ...</div>
</div>

And get number: 3

+15  A: 

$("#center div").length will give you the count.

Philippe Leybaert
+1; You could also use `$("div.name").length` if you explicitly want to count all the `div` elements with the `class` attribute set to `name`
Giu
+1 to both of you. Clean and simple answer!
Tom
A: 

document.getElementsByTagName("div").length will give you the desired answer

Huthaifa Afanah
OP asks for "using jQuery" instead of plain old JS. Also, that yields 4, but I believe OP is looking to count `div.name` only.
BoltClock
Would also return 4 and not 3 as requested
jkilbride
A: 
<div id = "center">
  <div class ="name">text text</div>
  <div class ="name">
       <div class ="SomeOtherDiv">bla bla</div>
  </div>
  <div class ="name">text ...</div>
</div>

$('#center div').length // Result: 4

$('#center > div').length // Result: 3

IgalSt