0

i want to add one Class to an image if it have alt attribute and one class to an image which doesnot have an alt attribute.

i tried this but its not working

if ($(img).hasAttr('alt'))
{
    this.addClass("haveAlt");   
}
José Ricardo Pla
  • 1,043
  • 10
  • 16
simr
  • 9
  • 2

1 Answers1

4

You can use attribute selector:

$('img[alt]').addClass('haveAlt');

For the ones which don't have alt attribute, use :not selector:

$('img:not([alt])').addClass('noAlt');

As as side note to hande both cases in one function call, you can use:

$('img').addClass(function(){
    return this.alt ? "haveAlt": "noAlt";
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155