Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class via jquery but only when not exists

Tags:

jquery

list

I would like to add a class (class="bbox") to a ul-list but only if no class exists. This is what i have so far. How do I check with jquery if a class exists in the ul-tag?

$("ul").addClass("bbox");
like image 782
Mark Henry Avatar asked Nov 25 '11 08:11

Mark Henry


3 Answers

Just use $('.selector').addClass("myClass");.

The jQuery add/remove class functions both check for duplicates internally, meaning that calling addClass twice only will add the class once.

like image 64
Tormod Haugene Avatar answered Nov 07 '22 00:11

Tormod Haugene


If you want to check if a specific class exists then:

 if(!$("ul").hasClass("class-name")){
    $("ul").addClass("bbox");
 }

If you want to check if any class exists:

if ($('ul').attr('class') == '') {
    $("ul").addClass("bbox");
}
like image 58
Matt Asbury Avatar answered Nov 07 '22 00:11

Matt Asbury


karim79 you almost got it !

let me correct you

$("ul:not([class*='bbox'])").addClass("bbox");

You match the tag with absolute no classes, and if ul had other classes the matching wouldn't be made. You got to search for the exactly class you wish to add. Like .hasClass aproach.

hope it helps

like image 24
aemonge Avatar answered Nov 06 '22 23:11

aemonge