Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out an element's classes in 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 replace "bar," I just want to be able to access the classes that are NOT bar. Thanks.

like image 991
stinkycheeseman Avatar asked Nov 08 '11 15:11

stinkycheeseman


1 Answers

There's no 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(" ")); 
});

See it in action here: http://jsfiddle.net/PpUeX/2

like image 150
Matt Avatar answered Sep 27 '22 20:09

Matt