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>
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>