Possible Duplicate:
Get Class List for Element with jQuery
If I have something like this, I can get the id of the clicked selector by doing this.
$('#one, #two, #three').click(function(){
alert(this.id)
})
My question is if I have classes instead of id's, how do i get the classname of the clicked selector.
$('.one, .two, .three').click(function(){
// ??????
})
EDIT:
The clicked elements may have multiple classes, and I wish to isolate the class that was used to initially select the element.
You'd use the native .className
property.
this.className
It's this.className
instead of this.class
because class
is a reserved word in JavaScript, and some browsers haven't allowed reserved words to be used as property names.
It sounds like there could be multiple classes on an element. To isolate one, you can use $.grep
with $.inArray
.
var classes = ['one','two','three'];
$('.' + classes.join(',.')).click(function(){
var classNames = this.className.split(/\s+/);
var cls = $.grep(classNames, function(c, i) {
return $.inArray(c, classes) !== -1;
})[0];
alert(cls);
});
DEMO: http://jsfiddle.net/rFT8j/
Or you could use $.each
instead of $.grep
.
var classes = ['one','two','three'];
$('.' + classes.join(',.')).click(function(){
var classNames = this.className.split(/\s+/);
var cls;
$.each(classNames, function(i, c) {
if( $.inArray(c, classes) !== -1 ) {
cls = c;
return false;
}
});
alert(cls);
});
DEMO: http://jsfiddle.net/rFT8j/1/
If you want something a little simpler, one solution would be to take advantage of closures, and assign separate handlers that each reference a different name in the variable scope...
var classes = ['one','two','three'];
$.each(classes, function(i, c) {
$('.' + c).click(function(){
alert(c);
});
});
DEMO: http://jsfiddle.net/rFT8j/3/
Just use JQuery's .attr to get the attribute class value
alert($(this).attr("class"));
$('.one, .two, .three').click(function(e){
console.log($(e.currentTarget).attr('class'))
})
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