Ask any question about JavaScript here... and get an instant response.
How can I prevent event bubbling while still using event delegation in my JavaScript application?
Asked on Nov 18, 2025
Answer
Event bubbling can be prevented by using the "stopPropagation" method on the event object. This allows you to use event delegation while stopping the event from bubbling up to parent elements.
<!-- BEGIN COPY / PASTE -->
document.querySelector("#parent").addEventListener("click", function(event) {
if (event.target.matches(".child")) {
console.log("Child element clicked");
event.stopPropagation(); // Prevents the event from bubbling up
}
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The code attaches a click event listener to the parent element with the ID "parent".
- It uses event delegation to check if the clicked target matches the ".child" selector.
- "event.stopPropagation()" is called to prevent the event from bubbling up to other parent elements.
- This approach allows handling events efficiently with fewer listeners.
Recommended Links:
