4

I waded through a TON of terrible js "solutions" for how to simply make collapsible nested list(s).

This is what I eventually came up with.

I'm posting here in the hopes the next guy won't have to deal with all the rufuse out there.

Otherwise feel free to add your own! maybe jquery free method if you can manage it?

miken32
  • 42,008
  • 16
  • 111
  • 154
Apollo Creed
  • 219
  • 3
  • 18

1 Answers1

5

css:

ul>li>ul {
    display: none;
}

js/jquery

$('li').click(function(e){
    e.stopPropagation();
    if(this.getElementsByTagName("ul")[0].style.display =="block")
        $(this).find("ul").slideUp();
    else
        $(this).children(":first").slideDown();
});

jfiddle

Apollo Creed
  • 219
  • 3
  • 18
  • ChatGPT translated to vanillaJS: document.querySelectorAll('li').forEach(function(listItem){ listItem.addEventListener('click', function(e){ e.stopPropagation(); let firstUl = this.getElementsByTagName("ul")[0]; if(firstUl.style.display === "block") { firstUl.style.display = "none"; } else { let firstChild = this.children[0]; if(firstChild.tagName === "UL") { firstChild.style.display = "block"; } } }); }); – xpmatteo Jun 27 '23 at 16:07