Home > Net >  Avoid Triggering Event For 1st Level When Clicking on 2nd Level of Nested HTML Elements (Using JQuer
Avoid Triggering Event For 1st Level When Clicking on 2nd Level of Nested HTML Elements (Using JQuer

Time:10-14

I have this HTML code:

<ul class="menu">
  <li>
     li first generation element
     <ul class="sub-menu">
        <li>
           li second generation element
        </li>
     </ul>
  </li>
  ...More li's first generation elements with ul's inside
</ul>

And this JQuery event:

$(".menu > li").click(function(){
    alert("click");
})

The problem that I am running into is that when I click on second generation li elements the event is being fired, this is because the first generation li element is being clicked too. This is causing that the event is fired in a wrong li element. I only want that this event fires when first generation of li elements are clicked.

How can I solve this?.

CodePudding user response:

The second LI is inside the first LI.

Use:

e.stopPropagation()

OR

e.preventDefault();

stopPropagation Docs

CodePudding user response:

Or you can try this.

$('.menu>li').children().click(function(e){
    alert("Child Clicked");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
  <li>
     li first generation element
     <ul class="sub-menu">
        <li>
           li second generation element
        </li>
     </ul>
  </li>
  ...More li's first generation elements with ul's inside
</ul>

The JQuery prevent the event from occuring on parent elements

  • Related