javascripthtmlonclickevent-bubblingevent-capturing

How to have a different onClick event for the child element without affecting the parent one?


Having the following structure:

<div class="the-parent">
  <div>
    <a onClick="doParentStuff()">
      <div>
        <i onClick="doChildStuff()"></i>
      </div>
    </a>
  </div>
</div>

Now, when the child element (icon) is clicked it logs the content of doChildStuff() but afterwards it also logs the content of doParentStuff().

Is there a way to call doChildStuff only when the icon is clicked and call doParentStuff when everything else inside the-parent div is clicked?


Solution

  • When the child is clicked, you must stopPropagation of the event:

    function doChildStuff(e) {
      e.stopPropagation();
      console.log('child clicked');
    }
    
    function doParentStuff() {
      console.log('parent clicked');
    }
    <div class="the-parent">
      <div>
        <a onClick="doParentStuff()">
          <div>
            Test
            <button onClick="doChildStuff(event)">Child</button>
          </div>
        </a>
      </div>
    </div>