Removing multiple classes (jQuery)

前端 未结 8 1920
醉梦人生
醉梦人生 2020-11-30 16:56

Is there any better way to rewrite this:

$(\'element\').removeClass(\'class1\').removeClass(\'class2\');

I cannot use removeC

相关标签:
8条回答
  • 2020-11-30 17:23

    The documentation says:

    class (Optional) String
    One or more CSS classes to remove from the elements, these are separated by spaces.

    Example:

    Remove the class 'blue' and 'under' from the matched elements.

    $("p:odd").removeClass("blue under");
    
    0 讨论(0)
  • 2020-11-30 17:24

    Separate classes by white space

    $('element').removeClass('class1 class2');
    
    0 讨论(0)
  • 2020-11-30 17:24

    Since jQuery 3.3.0, it is possible to pass arrays to .addClass(), .removeClass() and toggleClass(), which makes it easier if there is any logic which determines which classes should be added or removed, as you don't need to mess around with the space-delimited strings.

    $("div").removeClass(["class1", "class2"]); 
    
    0 讨论(0)
  • 2020-11-30 17:29

    There are many ways can do that!

    jQuery

    1. remove all class
      $("element").removeClass();
      OR
      $("#item").removeAttr('class');
      OR
      $("#item").attr('class', '');
      OR
      $('#item')[0].className = '';

    2. remove multi class
      $("element").removeClass("class1 ... classn");
      OR
      $("element").removeClass("class1").removeClass("...").removeClass("classn");

    Vanilla Javascript

    1. remove all class

    // remove all items all class  
    const items = document.querySelectorAll('item');
    for (let i = 0; i < items.length; i++) {
        items[i].className = '';
    }

    1. remove multi class

    // only remove all class of first item
    const item1 = document.querySelector('item');
    item1.className = '';

    0 讨论(0)
  • 2020-11-30 17:32

    You must be separate those classes which you want to remove by white space$('selector').removeClass('class1 class2');

    0 讨论(0)
  • 2020-11-30 17:34

    jQuery .removeClass() documentation.

    One or more CSS classes to remove from the elements, these are separated by spaces.

    0 讨论(0)
提交回复
热议问题