Reputation: 11
hi I am using this code below to count the img elements inside the div gallery
<script type="text/javascript">
var numimg=$("#gallery > img").size();
document.write(numimg);
</script>
<div class="slide" id="gallery">
<img src="images/6.jpg"/>
<img src="images/7.jpg"/>
<img src="images/8.jpg"/>
<img src="images/9.jpg"/>
<img src="images/10.jpg"/>
<img src="images/11.jpg"/>
</div>
the value i am recieving is 0, when there are 6 img elements. I need to get real number of child elements within div element. Can anybody help me out please.
Upvotes: 0
Views: 2472
Reputation: 110
Pretty sure you need to do demo here
$(function(){
var c = $('#gallery img').length;
$('#imgcount').html(c);
});
Upvotes: 0
Reputation: 27382
Replace
$("#gallery > img").size();
with
$("#gallery > img").length;
and wrap code inside document.ready as below.
$(function(){
$("#gallery > img").length;
});
Upvotes: 1
Reputation: 388436
There are multiple problems, your code needs to be inside the dom ready handler, after dom ready don't use document.write
, and use the length
property to get the number of child elements
jQuery(function(){
var numimg=$("#gallery > img").length;
$('body').append(numimg)
})
If you want to add the count to specific location of the page, then you can add a place holder element and then add the content to it
<span id="imgcount"></span>
<div class="slide" id="gallery">
<img src="images/6.jpg"/>
<img src="images/7.jpg"/>
<img src="images/8.jpg"/>
<img src="images/9.jpg"/>
<img src="images/10.jpg"/>
<img src="images/11.jpg"/>
</div>
then
jQuery(function(){
var numimg=$("#gallery > img").length;
$('#imgcount').html(numimg)
})
Demo: Fiddle
Upvotes: 1