javascripthtmljquerycssgoogle-web-designer

How to convert simple html list to multilevel using jquery


I have this code

in HTML:

<ul>
    <li><a href=''>Item</a></li>
    <li><a href=''>_subitem</a></li>
    <li><a href=''>_subitem</a></li>
    <li><a href=''>_subitem</a></li>
    <li><a href=''>__sub-subitem</a></li>
    <li><a href=''>__sub-subitem</a></li>
</ul>

Looks like this in browser:

    Item
        _subitem
        _subitem
        _subitem
            __sub-subitem
            __sub-subitem

Now I want a jquery solution to convert the above code to nested unordered HTML list like below.

<ul>
    <li>
        <a href=''>Item</a>
        <ul>
            <li><a href=''>subitem</a></li>
            <li><a href=''>subitem</a></li>
            <li>
                <a href=''>subitem</a>
                <ul>
                    <li><a href=''>sub-subitem</a></li>
                    <li><a href=''>sub-subitem</a></li>
                </ul>
            </li>
        <ul>
    </li>
<ul>

Please someone help me I am not finding any solution for this.


Solution

  • I count '_' for find level of sub items and also store each level's parent in parentLi variable which is an array and append each sub item to itself parent.

    function doIt() {
      let ul = document.createElement("ul");
      let parentLi = [];
      $("ul li a").each(function() {
        let level = ($(this).text().match(/_/g) || []).length;
        if (level === 0) {
          let li = document.createElement("li");
          let a = document.createElement("a");
          a.innerHTML = $(this).text()
          li.append(a);
          parentLi[level + 1] = li;
          ul.append(li);
        } else if (level > 0) {
          let ul = document.createElement("ul");
          let li = document.createElement("li");
          let a = document.createElement("a");
          a.innerHTML = $(this).text().replaceAll('_', '')
          li.append(a);
          parentLi[level + 1] = li;
          ul.append(li);
          parentLi[level].append(ul);
        }
      });
      $('#menu').append(ul);
    };
    
    doIt();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li><a href=''>Item</a></li>
      <li><a href=''>_subitem</a></li>
      <li><a href=''>__sub-subitem</a></li>
      <li><a href=''>__sub-subitem</a></li>
      <li><a href=''>_subitem</a></li>
      <li><a href=''>_subitem</a></li>
      <li><a href=''>Item1</a></li>
      <li><a href=''>_subitem</a></li>
      <li><a href=''>__sub-subitem</a></li>
      <li><a href=''>__sub-subitem</a></li>
      <li><a href=''>_subitem</a></li>
      <li><a href=''>_subitem</a></li>
      <li><a href=''>__sub-subitem</a></li>
      <li><a href=''>__sub-subitem</a></li>
    </ul>
    
    
    <div id='menu'></div>