I want to get the id of what ever element on a page when the user clicks on the page. There are several posts on here that show using 'this' works, but my code does not work with 'this'. The id returned is undefined. But I use the 'event' technique and it works.
Can someone explain the differences?
$(function(){
//document or 'body' tags both don't work
$('body').click(function(){
//var id = event.target.id;
var id=$(this).attr('id');
alert (id);
//returned undefined
});
});
This code works
$(function(){
$('body').click(function(event){
var id = event.target.id;
//var id=$(this).attr('id');
alert (id);
});});
I want to get the id of what ever element on a page when the user clicks on the page. There are several posts on here that show using 'this' works, but my code does not work with 'this'. The id returned is undefined. But I use the 'event' technique and it works.
Can someone explain the differences?
$(function(){
//document or 'body' tags both don't work
$('body').click(function(){
//var id = event.target.id;
var id=$(this).attr('id');
alert (id);
//returned undefined
});
});
This code works
$(function(){
$('body').click(function(event){
var id = event.target.id;
//var id=$(this).attr('id');
alert (id);
});});
Share
Improve this question
edited Oct 4, 2011 at 4:33
Shaz
15.9k4 gold badges43 silver badges60 bronze badges
asked Oct 4, 2011 at 4:22
JamexJamex
1,2225 gold badges23 silver badges34 bronze badges
1
- Because this will be the element that the listener is attached to (the body) and you likely haven't given it an id. The event target is the element that the event originally occured on, which is not necessarily the one calling the listener. – RobG Commented Oct 4, 2011 at 5:11
2 Answers
Reset to default 6Using the function below, the variable id
will refer to the body
element's id
itself.
$('body').click(function() {
var id = $(this).attr('id');
alert(id); // Will alert "undefined" if the <body> tag has no id
});
Using a different function like the one below actually does what you want by using event.target
, which is the element that is actually clicked within the body
element:
$('body').click(function(event) {
var id = event.target.id;
alert(id); // Will alert the id if the element has one
});
So, in short: event.target
is the element that is clicked, $(this)
would refer to the <body>
tag.
The first one is getting the body element id whereas the second one is getting the id of the element in the body that received the click event