Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get any element tagName on 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 ?

like image 587
Alex Avatar asked Dec 25 '22 08:12

Alex


1 Answers

Because you are attaching your event handler to the body element, this will always be the body. Instead, interrogate the event.target property:

$('body').click(function(e){
    var element = e.target.tagName;
    alert(element);
});

Example fiddle

like image 119
Rory McCrossan Avatar answered Dec 28 '22 05:12

Rory McCrossan