Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Bjørn-Martin Brunes
8,572 PointsList with hidden children that opens and close when parent are clicked on
Hi, I am trying to make a list with serveral children that open and close when clicked on the parent. I have tried to search the web and can only find something that works with one sub list, not that can open the children of Item 3-2. And I want the option for them to remain open after clicked not just when hovering over them. So several of them can stay open at the same time.
The list I want to make is long so it is essential to hide most of it.
<ul>
<li>Item 1
<ul>
<li>Item 1-1</li>
<li>Item 1-2</li>
</ul>
</li>
<li>Item 2</li>
<li>Item 3
<ul>
<li>Item 3-1</li>
<li>Item 3-2
<ul>
<li>Item 3-2-1</li>
<li>Item 3-2-2</li>
</ul>
</li>
<li>Item 3-3</li>
</ul>
</li>
<li>Item 4</li>
</ul>
1 Answer
Steven Parker
243,656 PointsI feel like I should probably charge for this, but it was fun to do:
var firstUL = document.querySelector("ul");
function collapse(ul) {
for (var li of ul.children) {
li.style.cursor = "default";
for (var x of li.children)
if (x.tagName == "UL") {
collapse(x);
x.style.display = "none";
li.style.cursor = "pointer";
}
}
}
collapse(firstUL);
firstUL.addEventListener("click", e => {
if (e.target.tagName == "LI")
for (var c of e.target.children)
if (c.tagName == "UL")
c.style.display = c.style.display == "none" ? "" : "none";
});