Search code examples
htmltreeview

How to expand tree view by default in html


I've been using the tree-view code from here: https://www.w3schools.com/howto/howto_js_treeview.asp. When the page first loads, the tree is fully collapsed. I want it to be fully expanded. Can someone help expand by default?

This is the html code from w3schools.com:


<ul id="myUL">
  <li><span class="caret">Beverages</span>
    <ul class="nested">
      <li>Water</li>
      <li>Coffee</li>
      <li><span class="caret">Tea</span>
        <ul class="nested">
          <li>Black Tea</li>
          <li>White Tea</li>
          <li><span class="caret">Green Tea</span>
            <ul class="nested">
              <li>Sencha</li>
              <li>Gyokuro</li>
              <li>Matcha</li>
              <li>Pi Lo Chun</li>
            </ul>
          </li>
        </ul>
      </li>  
    </ul>
  </li>
</ul>

This is the original javascript script from w3schools.com:

<script>
  var toggler = document.getElementsByClassName("caret");
  var i;

  for (i = 0; i < toggler.length; i++) {
    toggler[i].addEventListener("click", function() {
      this.parentElement.querySelector(".nested").classList.toggle("active");
      this.classList.toggle("caret-down");
    });
  }
</script>

Solution

  • Just add a for loop to toogle the class, with that you will have full expanded as the first view.

    <script>
      var toggler = document.getElementsByClassName("caret");
      var i;
    
      for (i = 0; i < toggler.length; i++) {
          toggler[i].parentElement.querySelector(".nested").classList.toggle("active");
          toggler[i].classList.toggle("caret-down");
    }
      for (i = 0; i < toggler.length; i++) {
        toggler[i].addEventListener("click", function() {
          this.parentElement.querySelector(".nested").classList.toggle("active");
          this.classList.toggle("caret-down");
        });
      }
    </script>