DannieCoderBoi
DannieCoderBoi

Reputation: 728

How to get class of any element clicked

I'm trying to get the class (if it is set) of any element that is clicked on the document, is this possible? I have tried:

$(document).on('click', function() {            
        var itemClass = $(this).attr('class');          
        if(typeof(itemClass) != "undefined" && itemClass !== null) {
            console.log('The item has class of:' + itemClass);
        } else {
            console.log('undefined or null');   
        }
    });

No matter what element I click on, the result in the console is always: undefined or null

Upvotes: 0

Views: 69

Answers (3)

Amit Kumar
Amit Kumar

Reputation: 5962

$(document).on('click', function(e) {
   var itemClass = e.target.className;
    alert(itemClass);
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use event object's target property to get the actual element which initiated the event.

The below will get the closest element with class attribute with respect to the clicked element.

$(document).on('click', function (e) {

    var itemClass = $(e.target).closest('[class]').attr('class');

    if (typeof (itemClass) != "undefined" && itemClass !== null) {
        console.log('The item has class of:' + itemClass);
    } else {
        console.log('undefined or null');
    }
});

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67197

Try to use the event.target property,

$(document).on('click', function(e) {
   var itemClass = e.target.className;
   // rest of your code goes here

NOTE: If there's no class set with the clicked element, then it would return undefined.

Upvotes: 2

Related Questions