Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...