admin管理员组

文章数量:1277361

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

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

Share Improve this question edited Mar 6, 2014 at 14:25 Leroy Mikenzi asked Mar 6, 2014 at 13:03 Leroy MikenziLeroy Mikenzi 8106 gold badges24 silver badges47 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

You could use:

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

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

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

本文标签: javascriptHow to check if an HTML element has no classStack Overflow