Reputation: 5361
My code goes like this.
<div id="some_id">
<img src="some_image.png">
<img src="some_image.png">
<div class="another_div"></div>
<div class="another_div"></div>
</div>
I want to count number of img tags inside that div element.
I found this from a similar question on stackoverflow which returns count of all the children.
var count = $("#some_id").children().length;
How do I modify this code or use some other function to count the number of img tags inside the div?
Upvotes: 17
Views: 46040
Reputation: 415
var count = $("#some_id img").length;
It will give you total length of images inside a div.
Upvotes: 0
Reputation: 895
Also (even though there are many right answers here), every of these methods in jQuery, such as children(), siblings(), parents(), closest(), etc. accept a jQuery selector as a parameter.
So doing
$("#some_id").children("img").length
should return what you need as well.
Upvotes: 1
Reputation: 12052
Or the plain version without jQuery:
document.getElementById("some_id").getElementsByTagName("img").length
Upvotes: 4
Reputation: 4591
Count img inside #some_div:
$("#some_id img").length
If you want only the direct children, not all descendants:
$("#some_id > img").length
Upvotes: 36
Reputation: 1720
var count = $("#some_id img").length
Select the image tags like this.
Upvotes: 7