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 06, 2026
Answer
Event bubbling is a process where an event propagates from the target element up through the DOM tree. To prevent this, you can use the "stopPropagation" method on the event object. Here's a simple example:
<!-- BEGIN COPY / PASTE -->
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
document.getElementById('child').addEventListener('click', function(event) {
event.stopPropagation();
alert('Button clicked!');
});
document.getElementById('parent').addEventListener('click', function() {
alert('Parent clicked!');
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "stopPropagation" method is called on the event object within the child element's event listener.
- This prevents the event from bubbling up to the parent element.
- The alert "Parent clicked!" will not be shown when the button is clicked.
- Always ensure you have a valid reason to stop event propagation to avoid unexpected behavior in complex applications.
Recommended Links:
