Mark Henry
Mark Henry

Reputation: 2699

add class via jquery but only when not exists

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

Upvotes: 72

Views: 90239

Answers (8)

Pranjalee R
Pranjalee R

Reputation: 11

To add a class (class="bbox") to a ul-list only if no class exists:

if (!$('ul').attr('class') == '') {
    $("ul").addClass("bbox");
}

Upvotes: 0

Danial
Danial

Reputation: 1614

If I'm toggling between 2 classes I use this method

if (foo)
    $('button.btn-foo').removeClass('foo bar').addClass('foo');
if (bar)
    $('button.btn-foo').removeClass('foo bar').addClass('bar');

So I don't have to check the current setting of the button

Upvotes: 5

Tormod Haugene
Tormod Haugene

Reputation: 3686

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.

Upvotes: 84

Mahmoud
Mahmoud

Reputation: 936

you can use this code for adding class only when if not exist

$('.your-dom:not(.class-name)').addClass('class-name');

Upvotes: 4

Vishal Nair
Vishal Nair

Reputation: 2191

I was wondering this would work fine -->

$("ul").removeClass("bbox").addClass("bbox");

First it will remove if there is any and then add new one . Worked best for me as i am too lazy to type all that if thingy.

Upvotes: 15

aemonge
aemonge

Reputation: 2347

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

Upvotes: 26

Matt Asbury
Matt Asbury

Reputation: 5662

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

Upvotes: 60

karim79
karim79

Reputation: 342635

Concisely:

// fine, because nothing happens if 
// there are no matching elements
$("ul[class='']").addClass("bbox");

Upvotes: 2

Related Questions