2299

I have a layout similar to this:

<div id="..."><img src="..."></div>

and would like to use a jQuery selector to select the child img inside the div on click.

To get the div, I've got this selector:

$(this)

How can I get the child img using a selector?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Alex
  • 25,366
  • 5
  • 27
  • 36

19 Answers19

2902

The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.

jQuery("img", this);

Which is the same as using .find() like this:

jQuery(this).find("img");

If the imgs you desire are only direct descendants of the clicked element, you can also use .children():

jQuery(this).children("img");
gnarf
  • 101,278
  • 24
  • 124
  • 158
Simon
  • 36,947
  • 2
  • 32
  • 27
  • 579
    for what it's worth: jQuery("img", this) is internally converted into: jQuery(this).find("img") So the second is ever so slightly faster. :) – Paul Irish Jan 08 '10 at 23:49
  • 24
    Thanks @Paul, I was worried that using find() was *wrong*, turns out it's the only way ;) – Agos Feb 17 '10 at 11:36
  • 5
    If the node is a direct child, wouldn't it be fastest to just do $(this).children('img'); ? – adamyonk Aug 05 '11 at 11:58
  • 11
    @adamyonk infact not, atleast not if this is anything to go by: http://jsperf.com/jquery-children-vs-find/3 – Simon Stender Boisen Oct 13 '11 at 06:21
  • 3
    I'm seeing the exact opposite of what @PaulIrish stated in this example - http://jsperf.com/jquery-selectors-comparison-a . Can anyone shed some light? Either I got the test-case wrong, or jquery changed this optimization in the last 4 years. – Jonathan Vanasco Nov 21 '13 at 20:19
  • 1
    Your test cases weren't fair - you were doing $(bar) when bar was already a jQuery object. Optimising the tests gets different results: http://jsperf.com/jquery-selectors-comparison-a/2 – Simon Nov 22 '13 at 13:33
  • 1
    "jQuery("img", this);" Is this documented on jQuery? – borayeris Dec 30 '13 at 02:05
  • 1
    jQuery(selector, context) is the first example in the docs - http://api.jquery.com/jquery/#jQuery-selector-context – Simon Jan 05 '14 at 21:38
  • 2
    `children()` is faster than `find()` according to this (September 29th, 2014): http://jsperf.com/jquery-children-vs-find/92 – Buttle Butkus Oct 28 '14 at 06:55
  • The simple thing to remember `find()` goes down and `closest()` go up and it will be much easier to work :) – Sagar Naliyapara Apr 25 '17 at 06:38
477

You could also use

$(this).find('img');

which would return all imgs that are descendants of the div

philnash
  • 53,704
  • 10
  • 46
  • 69
  • In general cases, it seems like `$(this).children('img')` would be better. e.g. `
    ` because presumably the user wants to find 1st-level imgs.
    – Buttle Butkus Oct 28 '14 at 06:47
140

If you need to get the first img that's down exactly one level, you can do

$(this).children("img:first")
rakslice
  • 7,846
  • 3
  • 47
  • 51
  • 6
    Does `:first` only match "*down exactly one level*", or does it match [the *"first"* `img`](http://api.jquery.com/first-selector/) that was found? – Ian Boyd May 15 '12 at 21:08
  • 3
    @IanBoyd, `.children()` is where the "down exactly one level" comes from and `:first` is where the "first" came from. – Tyler Crompton Jul 03 '12 at 21:43
  • @TylerCrompton What if the first `img` is in the second level down? – Ian Boyd Jul 03 '12 at 23:33
  • 3
    @IanBoyd, that element would be unaccounted for. It would only apply if you use `.find()` instead of `.children()` – Tyler Crompton Jul 04 '12 at 01:26
  • 2
    if you're using :first with a .find() be careful, jQuery seems to find all the descendants and then return the first element, very expensive sometimes – Clarence Liu Oct 08 '12 at 23:43
  • I wonder if you could do `$(this).children("div").children("img")` to find all grandchild `img` elements with `div` parents that are themselves children of `$(this)`... – Buttle Butkus Oct 28 '14 at 06:49
  • 1
    @ButtleButkus In the question, `this` was already a reference to the `
    ` containing the ``, however if you has multiple levels of tag to traverse from the reference you had then you definitely could definitely compose more than one `children()` call
    – rakslice Oct 28 '14 at 17:47
  • @rakslice I meant to say that `this` referenced the `
    ` containing the ``, and that that `
    ` might have child `
    `s with their own `` children. `
    `. So it seems you answered my question: `$(this).children("div").children("img")` would get the two ``s inside of the `inner` `
    `s? That is a good trick to know. Thank you.
    – Buttle Butkus Oct 28 '14 at 20:31
77

If your DIV tag is immediately followed by the IMG tag, you can also use:

$(this).next();
Book Of Zeus
  • 48,229
  • 18
  • 169
  • 166
Roccivic
  • 878
  • 6
  • 6
  • 16
    .next() is really fragile, unless you can always guarantee the element will be the next element, it's better to use a different method. In this case, the IMG is a descendant, not a sibling, of the div. – LocalPCGuy Dec 28 '11 at 18:12
  • The OP explicitly asked for a child img inside the div. – Giorgio Tempesta May 25 '18 at 10:15
71

The direct children is

$('> .child-class', this)
isherwood
  • 46,000
  • 15
  • 100
  • 132
Rayron Victor
  • 2,278
  • 1
  • 22
  • 24
41

You can find all img element of parent div like below

$(this).find('img') or $(this).children('img')

If you want specific img element you can write like this

$(this).children('img:nth(n)')  
// where n is the child place in parent list start from 0 onwards

Your div contain only one img element. So for this below is right

 $(this).find("img").attr("alt")
                  OR
  $(this).children("img").attr("alt")

But if your div contain more img element like below

<div class="mydiv">
    <img src="test.png" alt="3">
    <img src="test.png" alt="4">
</div>

then you can't use upper code to find alt value of second img element. So you can try this:

 $(this).find("img:last-child").attr("alt")
                   OR
 $(this).children("img:last-child").attr("alt")

This example shows a general idea that how you can find actual object within parent object. You can use classes to differentiate your child object. That is easy and fun. i.e.

<div class="mydiv">
    <img class='first' src="test.png" alt="3">
    <img class='second' src="test.png" alt="4">
</div>

You can do this as below :

 $(this).find(".first").attr("alt")

and more specific as:

 $(this).find("img.first").attr("alt")

You can use find or children as above code. For more visit Children http://api.jquery.com/children/ and Find http://api.jquery.com/find/. See example http://jsfiddle.net/lalitjs/Nx8a6/

Lalit Kumar Maurya
  • 4,957
  • 2
  • 27
  • 28
35

Ways to refer to a child in jQuery. I summarized it in the following jQuery:

$(this).find("img"); // any img tag child or grandchild etc...   
$(this).children("img"); //any img tag child that is direct descendant 
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag  child that is direct descendant 
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
Oskar
  • 2,366
  • 29
  • 35
31

Try this code:

$(this).children()[0]
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Maxam
  • 4,005
  • 2
  • 22
  • 25
31

Without knowing the ID of the DIV I think you could select the IMG like this:

$("#"+$(this).attr("id")+" img:first")
Adam
  • 389
  • 2
  • 2
23

You can use either of the following methods:

1 find():

$(this).find('img');

2 children():

$(this).children('img');
ann
  • 584
  • 1
  • 9
  • 19
Mike Clark
  • 1,774
  • 10
  • 21
21

jQuery's each is one option:

<div id="test">
    <img src="testing.png"/>
    <img src="testing1.png"/>
</div>

$('#test img').each(function(){
    console.log($(this).attr('src'));
});
Thirumalai murugan
  • 4,934
  • 8
  • 29
  • 53
15

You can use Child Selecor to reference the child elements available within the parent.

$(' > img', this).attr("src");

And the below is if you don't have reference to $(this) and you want to reference img available within a div from other function.

 $('#divid > img').attr("src");
Dennis R
  • 3,045
  • 1
  • 14
  • 23
12

Also this should work:

$("#id img")
Nilesh Thakkar
  • 2,807
  • 1
  • 24
  • 43
tetutato
  • 620
  • 5
  • 16
8

Here's a functional code, you can run it (it's a simple demonstration).

When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.

$(document).ready(function() {
  // When you click the DIV, you take it with "this"
  $('#my_div').click(function() {
    console.info('Initializing the tests..');
    console.log('Method #1: '+$(this).children('img'));
    console.log('Method #2: '+$(this).find('img'));
    // Here, i'm selecting the first ocorrence of <IMG>
    console.log('Method #3: '+$(this).find('img:eq(0)'));
  });
});
.the_div{
  background-color: yellow;
  width: 100%;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="my_div" class="the_div">
  <img src="...">
</div>

Hope it helps!

RPichioli
  • 2,907
  • 2
  • 22
  • 29
5

You may have 0 to many <img> tags inside of your <div>.

To find an element, use a .find().

To keep your code safe, use a .each().

Using .find() and .each() together prevents null reference errors in the case of 0 <img> elements while also allowing for handling of multiple <img> elements.

// Set the click handler on your div
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {

  // Find the image using.find() and .each()
  $(this).find("img").each(function() {
  
        var img = this;  // "this" is, now, scoped to the image element
        
        // Do something with the image
        $(this).animate({
          width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"
        }, 500);
        
  });
  
});
#mydiv {
  text-align: center;
  vertical-align: middle;
  background-color: #000000;
  cursor: pointer;
  padding: 50px;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="mydiv">
  <img src="" width="100" height="100"/>
</div>
Jason Williams
  • 2,540
  • 23
  • 33
  • why did you do this? `$("body").off("click", "#mydiv").on("click", "#mydiv", function() {` – Chris22 Sep 16 '17 at 01:18
  • I don't know how or where @Alex is using his snippet. So, I made it as safe and generic as possible. Attaching an event to body will make it so the event will trigger even if the div were not in the dom at the time the event was created. Clearing the event before creating a new one prevents the handler from running more than once when an event is triggered. It is not necessary to do it my way. Simply attaching the event to the div would also work. – Jason Williams Sep 26 '17 at 21:32
  • Thanks. I've seen this before in a script and while it worked for what the programmer intended, when I tried to use it for a modal window, the event still created several modals on single click. I guess I was using it wrong, but I wound up using `event.stopImmediatePropagation()` on the element to prevent that from happening. – Chris22 Sep 30 '17 at 01:48
4

$(document).ready(function() {
  // When you click the DIV, you take it with "this"
  $('#my_div').click(function() {
    console.info('Initializing the tests..');
    console.log('Method #1: '+$(this).children('img'));
    console.log('Method #2: '+$(this).find('img'));
    // Here, i'm selecting the first ocorrence of <IMG>
    console.log('Method #3: '+$(this).find('img:eq(0)'));
  });
});
.the_div{
  background-color: yellow;
  width: 100%;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="my_div" class="the_div">
  <img src="...">
</div>
Sumit Lahiri
  • 445
  • 5
  • 12
0

If your img is exactly first element inside div then try

$(this.firstChild);

$( "#box" ).click( function() {
  let img = $(this.firstChild);
  console.log({img});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
0

With native javascript you can use

if you've more than one image tag then use

this.querySelectorAll("img")

if only one image tag then us

this.querySelector("img")

Vishnu Prasanth G
  • 845
  • 10
  • 11
-1

You could use

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
 $(this).find('img');
</script>
Hassan Fayyaz
  • 377
  • 1
  • 4
  • 10