Search code examples
javascripthtmlonclickdom-events

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>

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>