开发者

apply rel attribute to <a> if child is img - jquery

I'm using jquery and am looking to dynamically add a rel attribute to tag but only if it's child is an image to add rel="lightbox". Something li开发者_开发百科ke the following....

if('a').children(img){

            $(this).attr('rel', 'lightbox');
        }

Any help/ advice is greatly appreciated.


Try this:

$('a > img').parent().attr('rel', 'lightbox');


You can use a sub-selector using jQuery. Sub-selectors matches children of the parent match. Use either space or > to delimit sub-selector :

// find all "img" children of "a"
$('a > img').each(function(){ $(this).attr('rel', 'lightbox'); });


$('img').parent('a').attr('rel', 'lightbox');


maybe something like this ? not sure !

$('a').find('img').each(function(i,v){
 $(v).parent().attr('rel','lightbox');
});

i like find() more than '>' because it much faster.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜