最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get any element tagName on click - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 11

The 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);
});
发布评论

评论列表(0)

  1. 暂无评论