Pergunta

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.

Foi útil?

Solução

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"

Outras dicas

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.

        function getDesiredClass( removedClassArr ){
            var classArray = $("selector").attr('class').split(" ");
            var desiredClassArray = [];
            for(var i = 0; i < classArray.length; i++ ){
               if ( !isUnDesiredClass(removedClassArr, classArray[i]) ){
                  desiredClassArray .push( classArray[i] );
               }
            }
            return desiredClassArray;
        }
       function isUnDesiredClass( removedClassArr , cls){
         for(var i = 0; i < removedClassArr.length; i++ ){
           if( removedClassArr[i] == cls ){
               return true;
            }
       }
      return false;
    }

You can check for individual classes using .hasClass.

$("div").hasClass("class");

This was answered here. Get class list for element with jQuery.

You can extend this to just get the strings in the array that are not "resizable, draggable or table"

var classes = $('div').not('.resizable, .draggable, .table').attr('class').split(' ');

have a look at this jsFiddle, I have something working like what you wanted.

Also, have a look at jQuery :not selectors

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top