SyntaxStudy
Sign Up
jQuery Tree View / Folder Structure
jQuery Intermediate 4 min read

Tree View / Folder Structure

Tree View Widget

Build an expandable/collapsible tree view for hierarchical data like file systems and category trees.

Example
$(function() {
  $(".tree-parent").prepend("<span class='tree-icon'>▶</span>");
  $(".tree-parent .tree-icon").on("click", function() {
    const $parent = $(this).parent();
    const $children = $parent.children(".tree-children");
    const open = $children.is(":visible");
    $children.slideToggle(150);
    $(this).text(open ? "▶" : "▼");
    $parent.attr("aria-expanded", !open);
  });
  // Keyboard support
  $(".tree-parent").on("keydown", function(e) {
    if (e.key === "Enter" || e.key === " ") { e.preventDefault(); $(this).find(".tree-icon:first").trigger("click"); }
  }).attr("tabindex","0").attr("role","treeitem");
});
Pro Tip

Add role="treeitem" and aria-expanded to each node for full ARIA tree widget compliance.