1

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

cazort
  • 516
  • 6
  • 19
Diego Arturo
  • 171
  • 1
  • 3
  • 15
  • There are many different ways of solving this. An inefficient one is by adding a condition inside your event that runs a check, perhaps looking to see if it's contained in another `
  • ` element, before firing the alert. A more efficient one would be to make your event trigger more targeted. You could run a loop once on page load, that would add individual listeners to each of the `
  • ` elements that you want to trigger the event. One solution requires giving the one level of elements its own class, see: https://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class
  • – cazort Oct 13 '21 at 17:23
  • Well this "perhaps looking to see if it's contained in another
  • element, before firing the alert" was my first approach, but then I realized that the element clicked was the first Li itself, so I have nothing to check before the alert because this wasn't the nested element. Adding $('.menu > li li').click(function (e) { e.stopPropagation(); }); solve the problem because i am telling to the code to check this event first (bubbling effect) then stops propagation of any other event.
  • – Diego Arturo Oct 13 '21 at 17:33