1

I have the following HTML structure:

<ul>
  <li>
      1- First Level
  </li>
  <li>
        <ul>
         <li>2 - Second Level</li>
       </ul>
 </li>
</ul>

I have the following jQuery

$(document).on('click','li',function(){
  var text = $(this).html();
  alert(text);
});

When I click on the li having the text 1- First Level, the click event is triggered.

But when I click on the sub li having text 2- Second Level, the trigger fires on the first li (since it is the parent)..

How can I trigger the click event on each li regardless of its status (parent/child)?

3 Answers 3

3

e.stopPropagation() will be the line you need to add, because any event bound on child bubbles up to the parent node, so result of it is both events occurs in the page.

e.stopPropagation() lets you stop the event to bubble up to the parent element in the DOM.

$(document).on('click','li',function(e){
  e.stopPropagation(); // stop the event to bubble up to the parent.
  var text = $(this).html();
  alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
      1- First Level
  </li>
  <li>
        <ul>
         <li>2 - Second Level</li>
       </ul>
 </li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

1

You need to stop event propogation using stopPropagation:

$(document).on('click','li',function(e){
   e.stopPropagation();
   var text = $(this).html();
   alert(text);
});

Comments

1

Try adding stopPropagation() in javascript

$(document).on('click','li',function(){
  var text = $(this).html();
  alert(text);
  stopPropagation();
});

Here is a fiddle https://jsfiddle.net/wLwccv7y/1/

Edited according to comments

1 Comment

that would stop the event on all elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.