1

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

kapa
  • 77,694
  • 21
  • 158
  • 175
Lawrence
  • 837
  • 3
  • 12
  • 26

6 Answers6

8

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.

DarthJDG
  • 16,511
  • 11
  • 49
  • 56
2
$("img[src*='31']").removeClass("myClass");
mattsven
  • 22,305
  • 11
  • 68
  • 104
2

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.

Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
1
$('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
    }
});
mak
  • 13,267
  • 5
  • 41
  • 47
0
var img = $('#img_to_look_at');
if ( img.attr('src').indexOf('31') > -1 ) img.removeClass('....');
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
-1

Hope this will solve your problem.

if(jQuery("img[src*='31']").size()>0){
    jQuery("img[src*='31']").removeClass('className')
};
mattsven
  • 22,305
  • 11
  • 68
  • 104
  • Better to use `.length` here. – mattsven Apr 28 '11 at 13:17
  • The `if` is completely unnecessary. If there are no elements like that, nothing will happen anyways. You also should not use the same selector twice, save it into a variable. – kapa Apr 28 '11 at 13:25