How to get the children of the $(this) selector?

JavascriptJqueryJquery Selectors

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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");

Solution 2 - Javascript

You could also use

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

which would return all imgs that are descendants of the div

Solution 3 - Javascript

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

$(this).children("img:first")

Solution 4 - Javascript

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

$(this).next();

Solution 5 - Javascript

The direct children is

$('> .child-class', this)

Solution 6 - Javascript

You can find all img element of parent div like below

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

If you want a 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 contains 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 objects within the parent object. You can use classes to differentiate your child's 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/

Solution 7 - Javascript

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

Solution 8 - Javascript

Try this code:

$(this).children()[0]

Solution 9 - Javascript

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

$("#"+$(this).attr("id")+" img:first")

Solution 10 - Javascript

You can use either of the following methods:

1 find():

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

2 children():

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

Solution 11 - Javascript

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'));
});

Solution 12 - Javascript

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");

Solution 13 - Javascript

Also this should work:

$("#id img")

Solution 14 - Javascript

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!

Solution 15 - Javascript

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>

Solution 16 - Javascript

$(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>

Solution 17 - Javascript

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>

Solution 18 - Javascript

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")

Solution 19 - Javascript

You could use

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
 $(this).find('img');
</script>
   

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptSimonView Answer on Stackoverflow
Solution 2 - JavascriptphilnashView Answer on Stackoverflow
Solution 3 - JavascriptraksliceView Answer on Stackoverflow
Solution 4 - JavascriptRoccivicView Answer on Stackoverflow
Solution 5 - JavascriptRayron VictorView Answer on Stackoverflow
Solution 6 - JavascriptLalit Kumar MauryaView Answer on Stackoverflow
Solution 7 - JavascriptOskarView Answer on Stackoverflow
Solution 8 - JavascriptMaxamView Answer on Stackoverflow
Solution 9 - JavascriptAdamView Answer on Stackoverflow
Solution 10 - JavascriptMike ClarkView Answer on Stackoverflow
Solution 11 - JavascriptThirumalai muruganView Answer on Stackoverflow
Solution 12 - JavascriptDennis RView Answer on Stackoverflow
Solution 13 - JavascripttetutatoView Answer on Stackoverflow
Solution 14 - JavascriptRPichioliView Answer on Stackoverflow
Solution 15 - JavascriptJason WilliamsView Answer on Stackoverflow
Solution 16 - JavascriptSumit LahiriView Answer on Stackoverflow
Solution 17 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 18 - JavascriptVishnu Prasanth GView Answer on Stackoverflow
Solution 19 - JavascriptHassan FayyazView Answer on Stackoverflow