开发者

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

开发者 https://www.devze.com 2023-02-11 00:10 出处:网络
I\'m using jquery and am looking to dynamically add a rel attribute totag but only if it\'s child is an image to add rel=\"lightbox\". Something li开发者_开发百科ke the following....

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

精彩评论

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