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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With