I have a layout similar to this:
and would like to use a jQuery selector to selec
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/
Without knowing the ID of the DIV I think you could select the IMG like this:
$("#"+$(this).attr("id")+" img:first")
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 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'));
});
Try this code:
$(this).children()[0]