add class via jquery but only when not exists

JqueryList

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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.

Solution 5 - Jquery

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

Solution 6 - Jquery

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

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

Solution 7 - Jquery

Concisely:

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

Solution 8 - Jquery

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark HenryView Question on Stackoverflow
Solution 1 - JqueryTormod HaugeneView Answer on Stackoverflow
Solution 2 - JqueryMatt AsburyView Answer on Stackoverflow
Solution 3 - JqueryaemongeView Answer on Stackoverflow
Solution 4 - JqueryVishal NairView Answer on Stackoverflow
Solution 5 - JqueryDanialView Answer on Stackoverflow
Solution 6 - JqueryMahmoudView Answer on Stackoverflow
Solution 7 - Jquerykarim79View Answer on Stackoverflow
Solution 8 - JquerypapapeepView Answer on Stackoverflow