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

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

I have a layout similar to this:

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:

How can I get the child img using a selector?


Solution 1:

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:


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


Solution 2:

You could also use


which would return all imgs that are descendants of the div

Solution 3:

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


Solution 4:

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


Solution 5:

The direct children is

$('> .child', this)

Solution 6:

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

// 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


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

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


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

You can do this as below :


and more specific as:


You can use find or children as above code. For more visit Children and Find
See example