Skip to content
Advertisement

How to get ul inside an li

<li class="cate-item"> 
<button class="cate-label" >item 1 </button>
    <ul class="sub-categ">
    <li> sub item 1</li>
    <li> sub item 2</li>
    <li> sub item 3</li>
    <li> sub item 4</li>
    </ul>
</li>

<li class="cate-item"> 
<button class="cate-label" >item 2 </button>
<ul class="sub-categ">
    <li> sub item 1</li>
    <li> sub item 2</li>
    <li> sub item 3</li>
    <li> sub item 4</li>
    </ul>
</li>

This li item is generated dynamically I want to toggle li on the cate-label button click. for that, I did the following code

  $(document).on("click", "#categoryList > li .cate-label", function () {
      var currentItem = $(this).closest("li");
      ItemToHide = $("#categoryList > li").not(currentItem);
        ItemToHide.removeClass("active-item");
    ItemToHide.find(".sub-cate").hide();
      currentItem.toggleClass("active-item");
     
     
     }
     
     );

when I try to hide item using ItemToHide.find(“.sub-cate”).hide(); it didn’t hide anything . I tried to find the length of the item using ItemToHide.find(“.sub-cate”).length but it returned 0.

Advertisement

Answer

Lower your event handling to something closer. I wrapped everything in a <menu> tag and registered the click event to it instead of document. It doesn’t make much of a difference performance wise but I suggest it because it’s looks as if your perspective is skewed if dealing with a larger view of the DOM and you’ll be error prone:

var currentItem = $(this).closest("li");
      ItemToHide = $("#categoryList > li").not(currentItem);
        ItemToHide.removeClass("active-item");
    ItemToHide.find(".sub-cate").hide();
      currentItem.toggleClass("active-item");

That nightmare is now:

$(this).next('.sub-categ').toggle('ease-out');

$('menu').on("click", ".cate-label", toggleList);

function toggleList(e) {
  $(this).next('.sub-categ').toggle('ease-out');
};
<menu>
  <li class="cate-item">
    <button class="cate-label">item 1 </button>
    <ul class="sub-categ">
      <li> sub item 1</li>
      <li> sub item 2</li>
      <li> sub item 3</li>
      <li> sub item 4</li>
    </ul>
  </li>

  <li class="cate-item">
    <button class="cate-label">item 2 </button>
    <ul class="sub-categ">
      <li> sub item 1</li>
      <li> sub item 2</li>
      <li> sub item 3</li>
      <li> sub item 4</li>
    </ul>
  </li>
</menu>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement