Filter element classes in jQuery?
What is the most efficient way to filter the class list for 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 that I could write a for loop to go through ev.currentTarget.classList, but I want to know if there is a better way.
EDIT: I would like to clarify that I want the warning to tell me "foo" and "bim". I do not want to replace "bar", I just want to have access to classes that are not bars. Thanks.
There is no jQuery way to do 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 here: http://jsfiddle.net/PpUeX/2
You can get the entire class string from an element using jQuery.fn.attr() and then split() into an array with which you can do whatever you want.
$("div.bar").click(function(ev) { var classes = $(this).attr('class').split(' '); // [0:'foo', 1:'bar'] }); EDIT: As for providing the "jQuery" output for all bar classes, you can make a temporary clone() 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'] });