Home > Enterprise >  Convert a simple unordered list into a nested list depending on the content of its list items
Convert a simple unordered list into a nested list depending on the content of its list items

Time:11-10

I have been looking for a solution that can help me to convert a single level html list into a multi level one.

The HTML Code looks like this before the conversion:

<ul>
    <li><a>Main</a></li>
    <li><a>_Sub Menu</a></li>
    <li><a>__Sub Sub Menu-1</a></li>
    <li><a>__Sub Sub Menu-2</a></li>
    <li><a>__Sub Sub Menu-3</a></li>
</ul>

The desired output after the conversion is:

<ul>
    <li>
        <a>Main</a>
        <ul>
            <li>
                <a>Sub Menu</a>
                <ul>
                    <li><a>Sub Sub Menu-1</a></li>
                    <li><a>Sub Sub Menu-2</a></li>
                    <li><a>Sub Sub Menu-3</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Here is the jQuery plugin code I already have: (it does the job, but i need it in plain Javascript)

! function(a) {
  a.fn.menuMaker = function() {
    return this.each(function() {
      var $t = a(this),
        b = $t.find('.LinkList ul > li').children('a'),
        c = b.length;
      for (var i = 0; i < c; i  ) {
        var d = b.eq(i),
          h = d.text();
        if (h.charAt(0) !== '_') {
          var e = b.eq(i   1),
            j = e.text();
          if (j.charAt(0) === '_') {
            var m = d.parent();
            m.append('<ul />');
          }
        }
        if (h.charAt(0) === '_') {
          d.text(h.replace('_', ''));
          d.parent().appendTo(m.children('.sub-menu'));
        }
      }
      for (var i = 0; i < c; i  ) {
        var f = b.eq(i),
          k = f.text();
        if (k.charAt(0) !== '_') {
          var g = b.eq(i   1),
            l = g.text();
          if (l.charAt(0) === '_') {
            var n = f.parent();
            n.append('<ul />');
          }
        }
        if (k.charAt(0) === '_') {
          f.text(k.replace('_', ''));
          f.parent().appendTo(n.children('.sub-menu2'));
        }
      }
      $t.find('.LinkList ul li ul').parent('li').addClass('has-sub');
    });
  }
}(jQuery);

Here is the equivalent JavaScript code I wrote, but it's not working

  • Related