7

Possible Duplicate:
Can jQuery provide the tag name?

Hi!

This question is so basic i am ashamed asking but i tried to find the answer for 30 minutes without any result.

How do i find out what kind of element has been clicked in the code below.

$('*').click(function (event) {
 var this_element = $(this).???;
 return false;
})

What i am looking for is to have the this_element variable set to 'a' if it's a link, 'p' if it's a paragraph 'div' if...

Thanks!

Community
  • 1
  • 1
Marreone
  • 117
  • 1
  • 3
  • 7
  • See: http://stackoverflow.com/questions/341900/how-can-i-determine-the-element-type-of-a-matched-element-in-jquery and http://stackoverflow.com/questions/1532331/can-jquery-provide-the-tag-name and http://stackoverflow.com/questions/1864151/how-to-know-the-type-of-an-jquery-object ... – Shog9 Feb 25 '10 at 00:25
  • by the way, should include `event.stopPropagation();` to stop your click from being passed along to parent elements for no good reason. see the api docs: http://api.jquery.com/get/ – ghoppe Feb 25 '10 at 00:46
  • @ghoppe - `return false;` in jQuery event handles `.stopPropagation()` and `.preventDefault()` – gnarf Feb 25 '10 at 00:55
  • ah, did not realize! Thank you @gnarf. – ghoppe Feb 25 '10 at 01:05

2 Answers2

8

Try this:

$('*').click(function (event) {
    var this_element = this.tagName.toLowerCase();
    return false;
});

The this pointer refers to the actual element being acted upon. As part of the DOM Level 2 core, all DOM elements have a property called .tagName.

Xavi
  • 20,111
  • 14
  • 72
  • 63
  • Be sure to `.toLowerCase()` some browsers implement all caps for `.tagName` while others don't. – gnarf Feb 25 '10 at 00:54
  • It really depends on what you're doing with the tag name. It may not matter. But fair enough, I'll make the change. – Xavi Feb 25 '10 at 05:06
3
$(this).get(0).tagName;
ghoppe
  • 21,452
  • 3
  • 30
  • 21