Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get id of button inside main div when I clicked on button?

I have added onclick on main div. Whenever I click on its child elements, main div onclick is trigger. I cannot get id of the child element I clicked inside the main div using this.

Here is sample

<div id = 'main' onclick='console.log(this);'>
  <p> some paragraph </p>
  ...
  <button id='test' type="button">click</button>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create a function by passing the event. Then use event.target to get the id.

Demo:

<div id = 'main' onclick='handleClick(event);'>
  <p> some paragraph </p>
  
  <button id='test' type="button">click</button>
</div>

<script>
  function handleClick(event) {
    console.log(event.target.id);
  }
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading