Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get certain classes but not others

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, draggableor table. In this case i want abc shadow. How do I do this.

like image 407
Pinkie Avatar asked Oct 18 '11 19:10

Pinkie


3 Answers

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"
like image 147
Phrogz Avatar answered Sep 21 '22 20:09

Phrogz


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']);
like image 40
Felix Kling Avatar answered Sep 19 '22 20:09

Felix Kling


@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.

like image 20
James Hill Avatar answered Sep 19 '22 20:09

James Hill