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?
jQuery's
each
is one option:You can find all img element of parent div like below
If you want specific img element you can write like this
Your div contain only one img element. So for this below is right
But if your div contain more img element like below
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.
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 your DIV tag is immediately followed by the IMG tag, you can also use:
You may have 0 to many
<img>
tags inside of your<div>
.To find an element, use a
.find()
.To keep your code safe, use a
.each()
.Using
.find()
and.each()
together prevents null reference errors in the case of 0<img>
elements while also allowing for handling of multiple<img>
elements.