Skip to content

Instantly share code, notes, and snippets.

@atomize
Created October 20, 2018 22:56
Show Gist options
  • Save atomize/a9e63f3623eca1ac16ad228f0a397b20 to your computer and use it in GitHub Desktop.
Save atomize/a9e63f3623eca1ac16ad228f0a397b20 to your computer and use it in GitHub Desktop.
// move all text into <span>
// they occupy exactly the place necessary for the text,
for (let li of tree.querySelectorAll('li')) {
let span = document.createElement('span');
li.prepend(span);
span.append(span.nextSibling); // move the text node into span
}
// catch clicks on whole tree
tree.onclick = function(event) {
if (event.target.tagName != 'SPAN') {
return;
}
let childrenContainer = event.target.parentNode.querySelector('ul');
if (!childrenContainer) return; // no children
childrenContainer.hidden = !childrenContainer.hidden;
}
<html>
<head>
<style>
.tree span:hover {
font-weight: bold;
}
.tree span {
cursor: pointer;
}
</style>
<meta charset="utf-8">
</head>
<body>
<ul class="tree" id="tree">
<li>Animals
<ul>
<li>Mammals
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
</ul>
</li>
<li>Other
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<ul>
<li>Aquarium
<ul>
<li>Guppy</li>
<li>Angelfish</li>
</ul>
</li>
<li>Sea
<ul>
<li>Sea trout</li>
</ul>
</li>
</ul>
</li>
</ul>
<script src='collapseTree.js'></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment