$(this) selector and children?
74
I have a layout similar to this

I would like to use a jQuery selector to select the child img inside of the div on click

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

How do I get the img with a selector?
improve this question | comment
Kayleigh Beer Created at: 2013-11-13 17:07:21 UTC By Kayleigh Beer
9 Answers
0
jquery 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'));
});

0
Try this code:

$(this).children()[0]

0
The direct children is 

$('> .child', this)

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

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

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

$(this).next();

0
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/
0
If you need to get the first img that's down exactly one level, you can do 

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

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

jQuery("img", this);


Which is the same as

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


If the imgs are direct descendants of the clicked element, you can also use:

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

0
You could also use

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


which would return all imgs that are descendants of the div
Your Answer