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 04, 2026
Answer
Event bubbling can be prevented in JavaScript by using the "stopPropagation" method on the event object. This stops the event from propagating up the DOM tree.
<!-- BEGIN COPY / PASTE -->
document.querySelector("#myButton").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Button clicked, but event won't bubble up!");
});
document.querySelector("#parentDiv").addEventListener("click", function() {
console.log("This won't be logged if the button is clicked.");
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "stopPropagation" method is called on the event object to prevent the event from bubbling up to parent elements.
- The example shows a button inside a parent div; clicking the button will not trigger the parent's event listener.
- It is important to understand that "stopPropagation" only stops the event from bubbling, not from executing other event listeners on the same element.
- Always ensure that stopping propagation is necessary, as it can interfere with other event handling logic.
Recommended Links:
