How to create a tree view with CSS and JavaScript?

CSSWeb DevelopmentFront End Technology

To create a tree view with CSS and JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   ul, #treeUL {
      list-style-type: none;
   #treeUL {
      margin: 0;
      padding: 0;
   .rootTree {
      cursor: pointer;
      user-select: none;
      font-size: 18px;
      font-weight: bold;
      color: blue;
   li {
      font-size: 16px;
      color: crimson;
      font-weight: 500;
   .rootTree::before {
      content: "\25B6";
      color: black;
      display: inline-block;
      margin-right: 6px;
   .rootTree-down::before {
      transform: rotate(90deg);
   .children {
      display: none;
   .active {
      display: block;
<h1>Tree view example</h1>
<ul id="treeUL">
<span class="rootTree">Root</span>
<ul class="children">
<span class="rootTree">/home</span>
<ul class="children">
<span class="rootTree">/home/Desktop</span>
<ul class="children">
   var toggler = document.querySelectorAll(".rootTree");
   Array.from(toggler).forEach(item => {
      item.addEventListener("click", () => {
         item.parentElement .querySelector(".children") .classList.toggle("active");


The above code will produce the following output −

On expanding the tree by clicking on the caret −

Published on 08-May-2020 17:07:53