Javascript/jQuery - How do I obtain name of the class of clicked element?

In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:

Example: http://jsfiddle.net/wpNST/

$('div').click(function() {
    var theClass = this.className;  // "this" is the element clicked
    alert( theClass );
});

This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.

There are jQuery methods that do this as well, like .attr().

Example: http://jsfiddle.net/wpNST/1/

$('div').click(function() {
    var theClass = $(this).attr('class');
    alert( theClass );
});

Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.


This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.

jQuery

​$(window).click(function(e) {
    console.log(e); // then e.srcElement.className has the class
});​​​​

Javascript

window.onclick = function(e) {
    console.log(e); // then e.srcElement.className has the class
}​

Try it out

http://jsfiddle.net/M2Wvp/

Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.