Aariba
Aariba

Reputation: 1194

Conditionally add class to image by jquery

This JS replace image file name default.jpg to hqdefault.jpg from all images below. But now I'm trying to add class to Image, if Image src has img.youtube.com link on images by extending this JS.

JS:

$('#selector img').attr('src',function(i,e){
    return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});

HTML:

<div id="selector">
    <img src="http://img.youtube.com/vi/qDc_5zpBj7s/default.jpg">
    <img src="http://img.youtube.com/vi/ss7EJ-PW2Uk/default.jpg">
    <img src="http://img.youtube.com/vi/ktd4_rCHTNI/default.jpg">
    <img src="http://img.youtube.com/vi/0GTXMEPDpps/default.jpg">
</div>

Means, If image src has Youtube image then add a class .video to parent image.

Upvotes: 0

Views: 978

Answers (2)

Nilesh
Nilesh

Reputation: 41

You can add a condition before replacing and add video class.

$('#selector img').attr('src',function(i,e){
    if($(this).attr('src').search('img.youtube.com') > 0){
         $(this).addClass('video');
    }
    return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});

Upvotes: 1

jcubic
jcubic

Reputation: 66478

Try:

$('#selector img').each(function(i) {
    var self = $(this);
    var src = self.attr('src');
    if (src.match(/img.youtube.com/)) {
        self.attr('src', src.replace("/default.jpg","/hqdefault.jpg"));
        self.addClass('video');
    }
});

Upvotes: 3

Related Questions