Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You'll want to start by thinking about your HTML structure. You'll need some kind of nested elements to express the list. I would recommend using nested <code>&lt;ul&gt;</code> elements because it semantically represents your data structure.</p> <p>Don't worry about how many levels there are; if you do it right, the same code will work for a collapsible element at any level.</p> <p>You'll really have three tasks: knowing when the tree element is clicked on, finding its children, and toggling their visibility.</p> <p>You can use jQuery's <a href="http://api.jquery.com/click/" rel="nofollow">.click()</a> handler to determine when the element is clicked on. Be careful, though: if you have, for example, nested <code>&lt;li&gt;</code> elements, and you use <code>$('li').click</code> as your event, you'll catch multiple clicks for sub-elements (as they will also trigger their parent's <code>click</code> event). So you'll have to be a little clever with your selector.</p> <p>Once you're able to detect the click, then you can find any sub-items by using jQuery's <a href="http://api.jquery.com/children/" rel="nofollow">.children()</a> function.</p> <p>Finally, it's a simple matter of toggling the visibility of child elements, which you can do easily with jQuery's <a href="http://api.jquery.com/toggle/" rel="nofollow">.toggle()</a> function.</p> <p>Lastly, I agree with the sentiment of Josh's comment: why re-invent the wheel? If you're doing it to learn, that's great, and you can use the approach I outlined in this answer. If you just need it done, you should look into using an existing jQuery extension, like Josh's suggestion of <a href="http://jqueryui.com/demos/accordion/" rel="nofollow">Accordion</a> or <a href="http://jquery.bassistance.de/treeview/demo/" rel="nofollow">jQuery Treeview</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload