March 18, 2013
How to control jQuery events when you have nested HTML?
Question by Cristian David Jimenez Duarte
For example:
<ul>
<li>
first element
<ul>
<li> second element
<ul>
<li> third element </li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
$('li').click( function() {
alert('hello world!!!');
});
</script>
The output is:
THREE ALERTS WHEN I CLICK THE THIRD ELEMENT
TWO ALERTS WHEN I CLICK THE SECOND ELEMENT
ONE ALERT WHEN I CLICK THE FIRST ELEMENT
How to prevent with jQuery this?
What I’m needing is: ONE ALERT FOR EACH CLICK IN ANY ‘LI’ ELEMENT.
Answer by Starx
As you have nested li
elements. The click handler applies to all li
elements including the parent li
‘s.
You need to stop propagating the event bubble. So that once it execute the event handler, it does not goes up the DOM tree to trigger the same event.
$('li').click( function(e) {
alert('hello world!!!');
e.stopPropagation();
});