Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get clicked classname [duplicate]

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.

like image 472
Pinkie Avatar asked Feb 02 '12 20:02

Pinkie


3 Answers

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/

like image 68
4 revsuser1106925 Avatar answered Nov 10 '22 21:11

4 revsuser1106925


Just use JQuery's .attr to get the attribute class value

alert($(this).attr("class"));
like image 35
Henesnarfel Avatar answered Nov 10 '22 23:11

Henesnarfel


$('.one, .two, .three').click(function(e){
    console.log($(e.currentTarget).attr('class'))
})
like image 35
samccone Avatar answered Nov 10 '22 21:11

samccone