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