3

I would like to determine the number of images inside a certain div. I am fairly sure I have the code to select the elements I would like to count:

var imageCount = $("#work img").size(); 

And the div itself couldn't be simpler:

<div id="work" class="shown">
<img src="graphics/gallery/001.jpg" />  
<img src="graphics/gallery/002.jpg" />
</div>

But when I ask for

alert(imageCount);

It returns 0, not 2! What am I doing wrong? And yes, I am alerting inside a ready function so I know the elements are available...

gnarf
  • 105,192
  • 25
  • 127
  • 161
Isaac Lubow
  • 3,557
  • 5
  • 37
  • 53
  • 3
    [Works for me...](http://jsbin.com/uxene3) Whatever you're doing wrong, it's not evident to me from this question. What browser are you using? – Shog9 Jun 29 '10 at 04:28
  • 2
    For the record, your code works for me on FF and Chrome on Linux using jQuery 1.4.2. Maybe you are trying to alert it when the variable is out of scope? – TomWilsonFL Jun 29 '10 at 04:29

3 Answers3

3
var imgCount = $('#work > img').length

If this doesn't work, recheck your markup and make sure img elements are children.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • 1
    Thanks, it looks like using (document).ready wasn't enough. When I put the same snippet of code into the body (instead of the head), boom, it worked like a charm. PS I'm still using my original code, the size() method and the ">" was not necessary. – Isaac Lubow Jun 29 '10 at 07:52
-1

Looks like you are using jQuery. You can do this:

var imageCount = $("#work").children("img").length;
Jaanus
  • 17,688
  • 15
  • 65
  • 110
-3

off the top of my head something like..

 $("#work").children("img").length

for more information see this question count-immediate-child-div-elements-using-jquery

Community
  • 1
  • 1
Jacob
  • 1,242
  • 2
  • 9
  • 14