Lawrence
Lawrence

Reputation: 845

Remove class on IMG if filename contains a string

I am fairly new to the jQuery world but I am starting to get a better grasp of things.

I have come across a situation that I need a little help with, I was wondering how I would go about setting up a if statement that looks at a image filename and looks to see if it contains the number 31 , if it does remove a class that is attached.

Thank you ahead of time

Upvotes: 1

Views: 1407

Answers (6)

kapa
kapa

Reputation: 78721

A nice way would be to use a function as an argument for .removeClass().

$('img').removeClass(function () {
    if (this.src.replace(/^.*\//, '').indexOf('31') > -1) {
         return 'classname';
    }
    return false;
});

.replace(/^.*\//, '') will return only the filename (example on SO), so if there is a 31 in the URL somewhere else (like in /pix/31/image.jpg), removal won't happen.

The function should return the classname to be removed if conditions are met, and false otherwise (to indicate nothing should be removed).

You could replace the img selector with something more specific if you don't want to check on the whole page (add classes, or specify a context).

And the jsFiddle Demo.

Upvotes: 2

mak
mak

Reputation: 13405

$('img[src*="31"]').each(function() {
    // check if only the filename contains 31
    var filename = $(this).attr('src').substr($(this).attr('src').lastIndexOf('/'));
    if (filename.indexOf('31') != -1) {
        $(this).removeClass(); // will remove all classes the img had
    }
});

Upvotes: 1

Mamoon ur Rasheed
Mamoon ur Rasheed

Reputation: 317

Hope this will solve your problem.

if(jQuery("img[src*='31']").size()>0){
    jQuery("img[src*='31']").removeClass('className')
};

Upvotes: -1

mattsven
mattsven

Reputation: 23293

$("img[src*='31']").removeClass("myClass");

Upvotes: 2

Mike Thomsen
Mike Thomsen

Reputation: 37506

var img = $('#img_to_look_at');
if ( img.attr('src').indexOf('31') > -1 ) img.removeClass('....');

Upvotes: 0

DarthJDG
DarthJDG

Reputation: 16591

Try this:

$('img[src*="31"]').removeClass("classname");

Edit: actually it searches the whole src attribute, so it's only correct if your URL can't have "31" in it anywhere else.

Upvotes: 8

Related Questions