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

Viewed 1940673

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?

19 Answers

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

You could also use

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

which would return all imgs that are descendants of the div

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

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>

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

You could use

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