views:

94

answers:

4

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...

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

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

meder
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
A: 

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

Jacob
A: 

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

var imageCount = $("#work").children("img").length;
Jaanus
A: 
$("#work").find("img").length
jAndy
Thought id be nice and give an upvote. I prefer this answer.