JQuery get clicked classname

Possible duplicate:
Get list of classes for an element with jQuery

If I have something like this, I can get the identifier of the selected switch by doing this.

$('#one, #two, #three').click(function(){ alert(this.id) }) 

My question is, do I have classes instead of id, how to get the name of the click class.

 $('.one, .two, .three').click(function(){ // ?????? }) 

EDIT:

Clicked items can have multiple classes, and I want to highlight the class that was used to initially select the item.

+7
source share
4 answers

You must use your own .className property.

 this.className 

It is this.className instead of this.class , because class is a reserved word in JavaScript, and some browsers do not allow the use of reserved words as property names.


It looks like there can be several classes on an element. To isolate it, 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 can 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 need something a little simpler, one solution would be to use closure and assign to individual handlers so that each link refers to a different name in the variable area ...

 var classes = ['one','two','three']; $.each(classes, function(i, c) { $('.' + c).click(function(){ alert(c); }); }); 

DEMO: http://jsfiddle.net/rFT8j/3/

+11
source

Just use jQuery.attr to get the attribute class value

 alert($(this).attr("class")); 
+4
source
 $('.one, .two, .three').click(function(e){ console.log($(e.currentTarget).attr('class')) }) 
+3
source

The following two methods should work:

 $('#one, #two, #three').click(function(){ alert(this.className) }) $('#one, #two, #three').click(function(){ alert($(this).attr("class")) }) 
0
source

All Articles