Ahmad
Ahmad

Reputation: 12737

how to trigger click event on child element

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)?

Upvotes: 1

Views: 6488

Answers (3)

Oleg Glybchenko
Oleg Glybchenko

Reputation: 11

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

Upvotes: 1

Jai
Jai

Reputation: 74738

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>

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to stop event propogation using stopPropagation:

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

Upvotes: 1

Related Questions