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 −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   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;
   }
</style>
</head>
<body>
<h1>Tree view example</h1>
<ul id="treeUL">
<li>
<span class="rootTree">Root</span>
<ul class="children">
<li>/bin</li>
<li>/etc</li>
<li>
<span class="rootTree">/home</span>
<ul class="children">
<li>/home/Downloads</li>
<li>/home/Pictures/</li>
<li>
<span class="rootTree">/home/Desktop</span>
<ul class="children">
<li>/home/Desktop/file.txt</li>
<li>/home/Desktop/file1.mp3</li>
<li>/home/Desktop/file1.mp4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
   debugger;
   console.log('wow');
   var toggler = document.querySelectorAll(".rootTree");
   Array.from(toggler).forEach(item => {
      item.addEventListener("click", () => {
         item.parentElement .querySelector(".children") .classList.toggle("active");
         item.classList.toggle("rootTree-down");
      });
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On expanding the tree by clicking on the caret −

raja
Published on 08-May-2020 13:37:53
Advertisements