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

html - Click event in plain JavaScript - Stack Overflow

programmeradmin4浏览0评论

How to know the id of current Html element when clicking on a Html element using plain JavaScript?

<div id="myId">
  <div>
    <h2>First Div</h2>
  </div>
  <div>
    <h2>Second Div</h2>
  </div>
</div>

I would like to catch "myId" while I am clicking on the body of this div. That means I would like to get the ID of parent div when I click on First Div and Second Div.

My JS code is like below.

document.onclick = function(e) {
   alert(e.target.id)
}

How to know the id of current Html element when clicking on a Html element using plain JavaScript?

<div id="myId">
  <div>
    <h2>First Div</h2>
  </div>
  <div>
    <h2>Second Div</h2>
  </div>
</div>

I would like to catch "myId" while I am clicking on the body of this div. That means I would like to get the ID of parent div when I click on First Div and Second Div.

My JS code is like below.

document.onclick = function(e) {
   alert(e.target.id)
}
Share Improve this question edited Jan 26, 2018 at 12:33 abu abu asked Jan 26, 2018 at 12:19 abu abuabu abu 7,03223 gold badges82 silver badges155 bronze badges 1
  • 4 Depends on how you register event handler. Post your JS. – dfsq Commented Jan 26, 2018 at 12:20
Add a ment  | 

4 Answers 4

Reset to default 10

You can do that in the following way:

var div = document.getElementById('myId');
div.addEventListener('click', function(e){
  console.log(this.getAttribute('id'))
});
<div id="myId">
  <div>
    <h2>First Div</h2>
  </div>
  <div>
    <h2>Second Div</h2>
  </div>
</div>

event.currentTarget will be the dom element that the event is triggered by.

You can just write a function:

function showid(elem) { 
    var id = elem.id
    console.log(id)
    alert(id)
}

And in your HTML code:

<div id="myId" onclick="showid(this)">
  <div>
    <h2>First Div</h2>
  </div>
  <div>
    <h2>Second Div</h2>
  </div>
</div>

You can do it like this in vanilla JS, register an event handler on the document and retrieve the id of the clicked element:

document.addEventListener("click", function(e){
    alert(e.srcElement.id);
});
<p id="paragraph1">First Paragraph</p>

<button id="myButton">Click Me</button>

发布评论

评论列表(0)

  1. 暂无评论