Leroy Mikenzi
Leroy Mikenzi

Reputation: 810

How to check if an HTML element has no class

I want to append a class to an anchor tag, which as no class. Also this anchor tag is inside many DIV elements and h4 tag So h4 has a class say abc inside this h4 tag there is this anchor tag which doesn't have any class.This is what I tried but not working. I want to append a class to the anchor that doesn't have a class at present.

$(document).ready(function(){
 $('.abc a').hasClass(''){
   $(this).addClass('active');
 }
});

FIDDLE

Upvotes: 5

Views: 1547

Answers (3)

thebob
thebob

Reputation: 13

You can get the length of the attribute class.
If it is 0, then you can add a class

$(document).ready(function () {
    var classes = $('.abc a').attr('class');
    var cLength = classes.trim().length;
    if (clength==0) {
        $('.abc a').addClass('active');
    }
});

Upvotes: 0

Ash
Ash

Reputation: 1422

Another Solution :but @A. Wolff is better :

$(document).ready(function(){
   alert($('.abc a').attr('class'))
    if(!$('.abc a').attr('class')){
     $('.abc a').addClass('active');
    }
    alert($('.abc a').attr('class'))
});

Upvotes: 4

A. Wolff
A. Wolff

Reputation: 74420

You could use:

$('.abc a').filter(':not([class])').addClass('active');

Upvotes: 11

Related Questions