Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  42] [ 6]  / answers: 1 / hits: 55703  / 14 Years ago, thu, september 23, 2010, 12:00:00

I googled and googled and I concluded that it's very hard to get answer on my own.



I am trying to use jquery or JavaScript to get a property of clicked element. I can use this.hash for example - it returns hash value I presume.



Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?




  • jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.


  • JavaScript documentation? - is there even one comprehensive one? again please a link.


  • DOM documentation? - the one on W3C or where (link appreciated).




And what is this.hash? - DOM JavaScript or jQuery?


More From » jquery

 Answers
109

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.


[#95533] Monday, September 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denis

Total Points: 260
Total Questions: 87
Total Answers: 87

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;