开发者

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开发者_Python百科> 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>


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')


Use the children()[docs] method.

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

});

or if you're going to ensure no text nodes (including whitespace) before the image:

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

});

...But if you're just going to run jQuery methods, they iterate for you:

$(".customurl > img").attr(/*...*/);

This will apply the attr()[docs] method to each element in the result.

Also, some methods like .attr() will accept a callback as an argument.

$(".customurl > img").attr('src', function(i,src) {
     // give each <img> a calculated value for its src
    return 'some_new_value_' + i;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜