Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraldfullam/e24aebc0609788b88075 to your computer and use it in GitHub Desktop.
Save geraldfullam/e24aebc0609788b88075 to your computer and use it in GitHub Desktop.
jQuery plugin: $().removeClassExcept()

jQuery plugin: $().removeClassExcept()

Extend jQuery with $().removeClassExcept(); Removes all classes except those specified. Use as an alternative to .removeClass() when you only want to specify (or only know) which classes you want to keep.

A Pen by Gerald on CodePen.

License.

.blue {
color: blue;
}
.under {
text-decoration: underline;
}
.highlight {
background: yellow;
}
p {
margin: 0.5em;
font-size: 1em;
font-weight: bolder;
}
em {
color: gray;
}
pre {
margin: 0 0.5em;
}
.example {
margin: 1em;
}
<p><strong>Example:</strong> <em>Remove all classes except 'blue' from the matched elements.</em></p>
<pre class="prettyprint linenums"><code class="lang-js">
$('#ex1 p:even').removeClassExcept('blue');
</code></pre>
<div class="example" id="ex1">
<p class="blue under highlight">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under highlight">then</p>
<p class="blue under highlight">Goodbye</p>
</div>
<p><strong>Example:</strong> <em>Remove all classes except 'under' and 'highlight' from the matched elements.</em></p>
<pre class="prettyprint linenums"><code class="lang-js">
$('#ex2 p:odd').removeClassExcept('under highlight');
</code></pre>
<div class="example" id="ex2">
<p class="blue under highlight">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under highlight">then</p>
<p class="blue under highlight">Goodbye</p>
</div>
$(function () {
// Remove all classes except those specified
$('#ex1 p:even').removeClassExcept('blue');
$('#ex2 p:odd').removeClassExcept('under highlight');
});
(function ($) {
$.fn.removeClassExcept = function (options) {
options = options.replace(/ /g, '|');
var re = new RegExp('\\b(?:'+options+')\\b\\s*','g');
this.removeClass(function () {
return $(this).attr('class').replace(re, '');
});
return this;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment