How can I create a recursive menu in HTML / Javascript? -


take @ image below:

enter image description here

i want create menu don't know how start. thoughts?

it's pretty simple, in fact. consists in recursive nodelist.

you can achieve using ul, li , a simultaneously:

<ul>   <li>     <a>text here</a>     <!-- repeat -->   </li> </ul> 

and perform behavior, it's pretty simple too. must see if a element has nextelementsibling, , if has, it's because current node has child.

take @ example below created:

(function() {    var tree = document.getelementbyid('tree');      /* firstly, hide child items */    [].foreach.call(tree.queryselectorall('ul li a'), function(el, i) {      if (el.nextelementsibling)        el.nextelementsibling.classlist.add('hidden');    });      /* here make event delegation, add event handler hole tree */    tree.addeventlistener('click', function(e) {      var el = e.target;        /* if element clicked anchor, it's because it's node/leaf */      if (el.tagname === 'a') {        e.preventdefault();                /* if has nextelementsibling, it's because has children, it's node */        if (el.nextelementsibling) {          /* toggle visibility of child */          el.nextelementsibling.classlist.toggle('hidden');        } else {          // final child (leaf)          console.log(el.textcontent);        }      }    });  })();
.hidden {    display: none;  }
<div id="tree">    <ul>      <li>        <a>father</a>        <ul>          <li>            <a>son</a>          </li>        </ul>      </li>      <li>        <a>grandfather</a>        <ul>          <li>            <a>father</a>            <ul>              <li>                <a>son</a>              </li>            </ul>          </li>        </ul>      </li>      <li>        <a>father</a>        <ul>          <li>            <a>son</a>          </li>        </ul>      </li>    </ul>  </div>


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -