Jquery - Finding what element $(this) is [duplicate]
Asked Answered
G

2

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!

Guncotton answered 25/2, 2010 at 0:23 Comment(4)
See: #342400 and #1532831 and #1864651 ...Press
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: api.jquery.com/getSuh
@Suh - return false; in jQuery event handles .stopPropagation() and .preventDefault()Incommunicable
ah, did not realize! Thank you @gnarf.Suh
A
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.

Afterdinner answered 25/2, 2010 at 0:26 Comment(2)
Be sure to .toLowerCase() some browsers implement all caps for .tagName while others don't.Incommunicable
It really depends on what you're doing with the tag name. It may not matter. But fair enough, I'll make the change.Afterdinner
S
3
$(this).get(0).tagName;
Suh answered 25/2, 2010 at 0:27 Comment(5)
um, -1 for what? it works: jsbin.com/akohe/editSuh
donno, but it is somewhat redundant - $(this).get(0) should always equal this.Press
only true in this specific case (clicking on an element). $(this) may contain more than one DOM element…Suh
Well, sure... If this happened to be a selector string, or an array of elements, or some such. But that's not really relevant to this question.Press
I just get undefined values when I use thisTapeworm

© 2022 - 2024 — McMap. All rights reserved.