aBhijit
aBhijit

Reputation: 5361

Count number of img tags inside a div tag

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

Answers (10)

rescue1155
rescue1155

Reputation: 415

var count = $("#some_id img").length; 

It will give you total length of images inside a div.

Upvotes: 0

mara-mfa
mara-mfa

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

Darius
Darius

Reputation: 12052

Or the plain version without jQuery:

document.getElementById("some_id").getElementsByTagName("img").length

Upvotes: 4

Optimus Prime
Optimus Prime

Reputation: 6907

Use

var count = $("#some_id").find('img').length;

Upvotes: 13

use this

$("#some_id img").length

Upvotes: 3

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Use:

$("#some_id img").length

Here's a fiddle of it.

Upvotes: 1

jods
jods

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

Gintas K
Gintas K

Reputation: 1478

Try to get them like this:

var count = $("#some_id img").length;

Upvotes: 2

Pankucins
Pankucins

Reputation: 1720

var count = $("#some_id img").length

Select the image tags like this.

Upvotes: 7

Anton
Anton

Reputation: 32581

Try this

var count = $('#some_id').find('img').length;

Upvotes: 4

Related Questions