add class via jquery but only when not exists

前端 未结 7 941
刺人心
刺人心 2020-12-15 02:25

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

相关标签:
7条回答
  • 2020-12-15 03:01

    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

    0 讨论(0)
  • 2020-12-15 03:04

    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");
    }
    
    0 讨论(0)
  • 2020-12-15 03:04

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

    $('.your-dom:not(.class-name)').addClass('class-name');
    
    0 讨论(0)
  • 2020-12-15 03:10

    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.

    0 讨论(0)
  • 2020-12-15 03:18

    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.

    0 讨论(0)
  • 2020-12-15 03:18

    Concisely:

    // fine, because nothing happens if 
    // there are no matching elements
    $("ul[class='']").addClass("bbox");
    
    0 讨论(0)
提交回复
热议问题