1

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)
}
1
  • 4
    Depends on how you register event handler. Post your JS. Commented Jan 26, 2018 at 12:20

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

5 Comments

You solution is working when I click on Parent With id myId. But I would like to click on First Div and Second Div and get the id of parent div. Thanks
This will attach the event handler on every div, including the div's surrounding the h2's. You can target your selector by doing querySelectorAll('div[id]');
@abuabu change selector to 'div[id]` as mentioned above, this will then prevent this event getting attached to the div's without the id attribute.
@Mamun, you have now targeted a single element, div[id] will target any with any id attribute. eg. If you edited the html now to have <div id="myId2"> It won't work for this one.
@abuabu, please notice the update in the answer where I have used getElementById instead of querySelector which is most efficient in this case......thanks.
4

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

Comments

1

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.