Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select children of elements in an .each loop using JQuery?

I'm trying to select the <img> tags within each of my <a> tags that have the class name customurl.

I know that I can do this on one <a> like this:

$(".customurl img");

But I'm trying to work out what the syntax is in an .each like so:

$(".customurl").each(function(i)
{
    var t = $(this);

    // select child <img> within t
    // (for this iteration)
});

Here's a HTML snippet for further clarification:

<a class="customurl"><img src="blah" /> Some text</a>
<a class="customurl"><img src="blah" /> Some text</a>
<a class="customurl"><img src="blah" /> Some text</a>
like image 815
Marty Avatar asked Jul 04 '11 02:07

Marty


1 Answers

Use the .find('')

$(this).find('img')

or

t.find('img')

or this also works using the second param of .each():

$(".customurl").each(function(i, elem)
{
    $(elem).find('img')

If you only want the first image (assuming you have more than one):

$(this).find('img:first')

or

$(this).find('img:first-child')
like image 64
Samuel Liew Avatar answered Sep 28 '22 00:09

Samuel Liew