Remove all classes except one

76,800

Solution 1

Instead of doing it in 2 steps, you could just reset the entire value at once with attr by overwriting all of the class values with the class you want:

jQuery('#container div.cleanstate').attr('class', 'cleanstate');

Sample: http://jsfiddle.net/jtmKK/1/

Solution 2

Use attr to directly set the class attribute to the specific value you want:

$('#container div.cleanstate').attr('class','cleanstate');

Solution 3

With plain old JavaScript, not JQuery:

document.getElementById("container").className = "cleanstate";

Solution 4

Sometimes you need to keep some of the classes due to CSS animation, because as soon as you remove all classes, animation may not work. Instead, you can keep some classes and remove the rest like this:

$('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');

Solution 5

regarding to robs answer and for and for the sake of completeness you can also use querySelector with vanilla

document.querySelector('#container div.cleanstate').className = "cleanstate";
Share:
76,800

Related videos on Youtube

DarkGhostHunter
Author by

DarkGhostHunter

Freelance Web Designer & Web Developer

Updated on March 02, 2020

Comments

  • DarkGhostHunter
    DarkGhostHunter over 4 years

    Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:

    <div class="cleanstate"></div>
    

    Let's say that with some clicks and other things, the div gets a lot of classes

    <div class="cleanstate bgred paddingleft allcaptions ..."></div>
    

    So, how I can remove all the classes except one? The only idea I have come up is with this:

    $('#container div.cleanstate').removeClass().addClass('cleanstate');
    

    While removeClass() kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate') it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"

    I'm asking this because, in the real script, the div suffers various changes of classes.

    • pimvdb
      pimvdb over 13 years
      Get classes, split them with " " (space) and decide for each one whether or not to delete it?
  • goodeye
    goodeye about 9 years
    I like the answer to remove some classes. I think the code could be $('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');. I tried to edit, but once again stackoverflow doesn't let you be helpful.