Can I toggle class only on click of the parent li, and not the children?

The class should only toggle when clicking the top level li.

Codepen: https://codepen.io/flinch85/pen/zXdJav

 $( document ).ready(function() { 

  $('.menu-item-has-children').click(function(){
  $(this).toggleClass('sub-show');
});

  });

2 Answers

2
Pranav C Balan On Best Solutions

Check the target element a tag which is a direct child of .menu-item-has-children element using is() method(or prevent event bubbling up). Or alternately bind the event handler to the direct child tag a so it won't trigger when you clicked inside the nested list.

$(document).ready(function() {
  $(".menu-item-has-children").click(function(e) {
    if ($(e.target).is(".menu-item-has-children > a"))
      $(this).toggleClass("sub-show");
  });
});

$(document).ready(function() {
  $(".menu-item-has-children").click(function(e) {
    if ($(e.target).is(".menu-item-has-children > a"))
      $(this).toggleClass("sub-show");
  });
});
.sub-show {
  color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Home</a></li>

  <li class="menu-item-has-children"><a>Services</a>

    <ul class="sub-menu">
      <li><a href="#">Item</a></li>
    </ul>

  </li>

</ul>

2
Rajan On

For your Case,

You can simply change the selector:

   $('.menu-item-has-children > a').click(function(){
      $(this).toggleClass('sub-show');
    });

$(document).ready(function() {
  $('.menu-item-has-children > a').click(function() {
    $(this).toggleClass('sub-show');
  });
});
.sub-show {
  color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Home</a></li>

  <li class="menu-item-has-children"><a>Services</a>

    <ul class="sub-menu">
      <li><a href="#">Item</a></li>
    </ul>

  </li>

</ul>