<div id="parent">
Parent
<div id="child">
Child
<div id="descendant">Descendant</div>
</div>
</div>
#parent,
#child,
#descendant {
margin: 16px;
padding: 16px;
border: 4px solid #212121;
border-radius: 8px;
color: #fff;
font-weight: 500;
font-size: 20px;
text-transform: uppercase;
}
#parent {
background-color: #673ab7;
}
#child {
background-color: #448aff;
}
#descendant {
background-color: #ff9800;
}
const parent = document.querySelector("#parent");
const child = document.querySelector("#child");
const descendant = document.querySelector("#descendant");
parent.addEventListener("click", () => {
alert(
"Parent click handler. This alert will not appear when clicking on Descendant, the event will not reach here!"
);
});
child.addEventListener("click", () => {
alert(
"Child click handler. This alert will not appear when clicking on Descendant, the event will not reach here!"
);
});
descendant.addEventListener("click", (event) => {
event.stopPropagation();
alert("Descendant click handler");
});
View Compiled
This Pen doesn't use any external JavaScript resources.