Search code examples
javascriptevent-handlingdom-eventsevent-bubbling

Event handlers on parent and child div


Here is my HTML file

<div class="a">
    <div class="b">

    </div>
</div>
<script>
    document.querySelector('.a').onclick = ()=>{
        document.querySelector('.a').style.backgroundColor ='black'
    }
    document.querySelector('.b').onclick = ()=>{
        document.querySelector('.b').style.backgroundColor ='violet'
    }

</script>

When I click on the div with class 'b' ,the event handler on the div with class 'a' is also called. I want only the div with 'b' class event handler to be called. Can someone help on this?


Solution

  • This is Event Bubbling, which means that each event is triggered not only on the target element but also on its ancestor elements.

    To prevent this behavior, you can use Event.stopPropagation to stop the event from propagating to the ancestor elements of the target element.

    document.querySelector('.a').onclick = () => {
      document.querySelector('.a').style.backgroundColor = 'black'
    }
    
    document.querySelector('.b').onclick = (event) => {
      event.stopPropagation();
      document.querySelector('.b').style.backgroundColor = 'violet'
    }
    div { width: 100px; height: 100px; }
    .a { padding: 40px; background: red; }
    .b { background: blue; }
    <div class="a">
      a
      <div class="b">b</div>
    </div>