I need to take $('this') information from any element i click on the document.
I tried the following code:
$('body').click(function(){
var element = this.tagName; // or var element = $(this).prop('tagName');
alert(element);
});
The problem is that wherever i click i get only BODY element. If i click on a button or a div i want to get that element. How can i create something general to take every element i click ?
I need to take $('this') information from any element i click on the document.
I tried the following code:
$('body').click(function(){
var element = this.tagName; // or var element = $(this).prop('tagName');
alert(element);
});
The problem is that wherever i click i get only BODY element. If i click on a button or a div i want to get that element. How can i create something general to take every element i click ?
Share Improve this question asked May 24, 2014 at 12:56 AlexAlex 1,0737 gold badges24 silver badges43 bronze badges3 Answers
Reset to default 11The issue is because you are attaching your event handler to the body
element, therefore this
will always be the body
.
You should instead interrogate the target
property of the event, as this will always be a reference to the Element object which raised the event.
$('body').click(function(e) {
var element = e.target.tagName; // or var element = $(this).prop('tagName');
console.log(element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div class="foo">Foo</div>
<span class="foo">Foo <i>bar</i></div>
nodeName
$('body').click(function(e){
alert(e.target.nodeName);
});
http://quirksmode.org/dom/core/#t23
My advice is not to use tagName at all. nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.
it also looks like the performance is slightly better on some versions of chrome and firefox.
http://jsperf.com/tagname-vs-nodename/2
this
always refers to the element where the event handler is assigned, not where the event originated (well, you can change it, but it's pretty unusual to do so). For that, you need Event.target
:
$('body').click(function(event){
var element = event.target.tagName; // or var element = $(this).prop('tagName');
alert(element);
});