0
votes
  • I have a div element (parent element)(DIV1), which print the its name when onclick event gets triggered.
  • DIV1 has a child div element(DIV2) and it should print its name when onclick event triggered.
  • I have applied onclick on window also.

But when I click DIV2, it triggers onclick event of DIV1, so it print the name of parent div(DIV1) instead of DIV2.

So how do I make sure that when I click DIV1 it should trigger DIV1 onlick and when I click DIV2 it should trigger DIV2 onclick?

1
Please read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help.palaѕн
Capture the click on DIV2, and prevent propagation. See w3.org/TR/DOM-Level-3-Events/#event-flowTeemu
It depends on how you have written html code for it, there should be distinction between the two divs else it'll be difficult for dom which div you gonna clickholla
Please provide the code when asking a question and at least you can provide a image of the arrangement of divs for more clarity.cypherdragon

1 Answers

2
votes

Use event.stopPropagation() to stop the propagation of click event of div2 to div1

const clickHandler = (e,str) => {
e.stopPropagation()
console.log(str)
}

document.getElementById('div1').addEventListener('click',e=>clickHandler(e,'div1'))
document.getElementById('div2').addEventListener('click',e=>clickHandler(e,'div2'))
<div id="div1">
div 1
  <div id="div2">
div 2
  </div>
</div>