Avoid the use of Event.stopPropagation()
(unless you really, really know what you're doing).
An application, or third party code, should never stop or prevent an event to propagate throughout the application layers / components.
Instead, change your logic to implement a third function (like doStuff
) that will trigger a desired function depending on the Event.target.closest()
match
const doChildStuff = () => {
console.log("child stuff");
};
const doParentStuff = () => {
console.log("parent stuff");
};
const doStuff = (ev) => {
if (!ev.target.closest(".icon")) {
doParentStuff();
}
doChildStuff();
};
document.querySelectorAll(".anchor").forEach(elAnchor => {
elAnchor.addEventListener("click", doStuff);
});
<div class="the-parent">
<div>
<a class="anchor">
<div>
Link
<i class="icon">icon</i>
</div>
</a>
</div>
</div>
Also, stop using HTML inline on*
attribute handlers. Such code is hard to maintain and debug. JavaScript should be in one place only, and that's the respective tag or file. Use addEventListener instead.
Even if not asked, if you want to also separate the handler for the parent, simply put it into an else
block:
const doChildStuff = () => {
console.log("child stuff");
};
const doParentStuff = () => {
console.log("parent stuff");
};
const doStuff = (ev) => {
if (!ev.target.closest(".icon")) {
doParentStuff();
} else {
doChildStuff();
}
};
document.querySelectorAll(".anchor").forEach(elAnchor => {
elAnchor.addEventListener("click", doStuff);
});
<div class="the-parent">
<div>
<a class="anchor">
<div>
Link
<i class="icon">icon</i>
</div>
</a>
</div>
</div>