¿Filtrar las clases de un elemento en jQuery?

What is the most efficient way to filter the list of classes on a given element?

<div class="foo bar"></div>
<div class="bim bar"></div>

$("div.bar").click(function(ev) {
  alert("The non-bar class was:" + ???);
});

I know I could write a for-loop to go through the ev.currentTarget.classList but I want to know if there's a better way.

EDIT: I'd like to clarify that I want the alert to tell me "foo" and "bim." I don't want to reemplazar "bar," I just want to be able to access the classes that are NOT bar. Thanks.

preguntado el 08 de noviembre de 11 a las 15:11

2 Respuestas

No hay jQuery way to get this, but I would do:

$("div.bar").click(function(ev) {
    var nonBarClasses = (' ' + this.className + ' ').replace(' bar ', ' ').split(/ +/);

    nonBarClasses.shift();
    nonBarClasses.pop();

    // nonBarClasses is now an array, with each element a class that isn't `bar`

    alert("The non-bar class was: " + nonBarClasses.join(" ")); 
});

Véalo en acción aquí: http://jsfiddle.net/PpUeX/2

respondido 08 nov., 11:20

I think you're making it a little too complicated. What about jsfiddle.net/ZkucZ/1? - pimvdb

@pimvdb: I wouldn't say using a filter function over String.replace is less complicated; especially when the question is asking for efficiency. Plus Array.filter isn't supported in IE < 8. - Matt

Touche, I missed efficiency. Though, yours currently includes an extraneous element. jsfiddle.net/PpUeX/1 - pimvdb

You can get the entire class string from the element by using jQuery.fn.attr(), y entonces split() it into an array, with which you can do anything you want.

$("div.bar").click(function(ev) {
  var classes = $(this).attr('class').split(' '); // [0:'foo', 1:'bar']
});

EDIT: As for providing a "jQuery"-way of getting all of the non-"bar" classes, you could make a temporary clone() of the clicked element and removeClass() the bar class before you do anything with it:

$("div.bar").click(function(ev) {
  var noBarClasses = $(this)
    .clone().removeClass('bar') // <-- no more "bar"
    .attr('class').split(' '); // [0:'foo']
});

respondido 08 nov., 11:20

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.