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

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?

This question is related to javascript jquery jquery-selectors

The answer is


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

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

$(this).next();

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

You could use

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

If your img is exactly first element inside div then try

$(this.firstChild);

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


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

Try this code:

$(this).children()[0]

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

You could also use

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

which would return all imgs that are descendants of the div


You could use

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

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

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

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/


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


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/


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

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


Try this code:

$(this).children()[0]

You could also use

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

which would return all imgs that are descendants of the div


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

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

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.

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

Hope it helps!


The direct children is

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

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.

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


Try this code:

$(this).children()[0]

Also this should work:

$("#id img")

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

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

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

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

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.

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


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

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

If your img is exactly first element inside div then try

$(this.firstChild);

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


You could also use

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

which would return all imgs that are descendants of the div


You can use either of the following methods:

1 find():

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

2 children():

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

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.

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

Hope it helps!


Try this code:

$(this).children()[0]

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

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

You can use either of the following methods:

1 find():

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

2 children():

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

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

The direct children is

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

Also this should work:

$("#id img")

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

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

$(this).next();

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value