Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent event bubbling in JavaScript?
Asked on Feb 21, 2026
Answer
Event bubbling can be prevented in JavaScript by using the "stopPropagation" method on the event object within an event handler. This method stops the event from propagating up the DOM tree.
<!-- BEGIN COPY / PASTE -->
document.getElementById("myButton").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Button clicked, event propagation stopped.");
});
document.getElementById("myDiv").addEventListener("click", function() {
console.log("Div clicked.");
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- In this example, clicking the button will log "Button clicked, event propagation stopped." and prevent the "Div clicked." message from appearing.
- "stopPropagation" is useful when you want an event to be handled only by the target element and not by any of its parent elements.
- Ensure you have elements with the IDs "myButton" and "myDiv" in your HTML for this code to work correctly.
Recommended Links:
