how to check whether an image have alt attribute or not in jquery

432 views Asked by At

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");   
}
1

There are 1 answers

3
A. Wolff On

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";
});