I have a div that looks like
<div class="draggable resizable abc table shadow"></div>
Clases are in no specific order. If I do $('div').attr('class')
then I get a list of all the classes for that div. What I want is to only get classes that are not resizable
, draggable
or table
. In this case i want abc shadow
. How do I do this.
var all = "draggable resizable abc table shadow";
var some = all.replace(/(?:^|\s)(resizable|draggable|table)(?=\s|$)/g, '');
console.log(some);
// " abc shadow"
console.log(some.replace(/^\s+|\s+$/g,''));
// "abc shadow"
console.log(some.split(/\s+/));
// ["", "abc", "shadow"]
Note that you don't need the second replace
(you don't need to strip off leading and trailing whitespace) if all you want is a string that's appropriate for setting the className
to.
But then, if you're trying to just remove a set of known classes from an element, far better to simply:
$(...).removeClass("draggable resizable table");
Alternative (without needing a regex):
var ignore = {resizable:1, draggable:1, table:1};
var all = "draggable resizable abc table shadow".split(' ');
for (var subset=[],i=all.length;i--;) if (!ignore[all[i]]) subset.push(all[i]);
console.log(subset);
// ["shadow","abc"]
console.log(subset.join(' '));
// "shadow abc"
A plugin:
(function($) {
$.fn.getClasses = function(exclude) {
var remove = {};
for(var i = exclude.length; i--;) {
remove[exclude[i]] = true;
}
return $.map(this.attr('class').split(/\s+/g), function(cls) {
return remove[cls] ? null : cls;
});
};
}(jQuery));
Usage:
var classes = $('div').getClasses(['resizable', 'draggable', 'table']);
@Phrogz answer is a good one. Apparently, he's a regex wiz. Since I don't know regex that well, here's my take on it:
var aryClasses = $("div").attr("class").split(" ");
var aryDesiredClasses = new Array();
for(var i = 0; i < aryClasses.length; i++) {
if(aryClasses[i] != "table"
&& aryClasses[i] != "resizable"
&& aryClasses[i] != "draggable")
aryDesiredClasses.push(aryClasses[i]);
}
alert(aryDesiredClasses.join(" "));
Here's a working fiddle to illustrate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With