$(this) selector and children?
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
jquery each is one option

<div id="test">
    <img src="testing.png"/>
    <img src="testing1.png"/>

$('#test img').each(function(){

Try this code:


The direct children is 

$('> .child', this)

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

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

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


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 http://api.jquery.com/children/ and Find http://api.jquery.com/find/. 
See example http://jsfiddle.net/lalitjs/Nx8a6/
If you need to get the first img that's down exactly one level, you can do 


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


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


You could also use


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