title: Programmatically create HTML list and show child elements on click
body: <p>I am trying to build an HTML list from a JSON array where if a list object contains a child array of "levels" then clicking on the list item should reveal the levels as subsequent list items. The levels should be hidden by default until parent is clicked on (see below for graphic)</p>
  
  <p>Please see my code attempt below</p>
  
  <pre><code>$('#menuList ul')
           .append(
               $('&lt;li&gt;&lt;/li&gt;')
                   .append(
                       $('&lt;a&gt;&lt;/a&gt;')
                           .attr('href', '#')
                           .click(function (e) {
  
                               if (result.levels) {
                                   //if child levels, show levels on parent click
                                   var thelevels = result.levels;
                                   thelevels.forEach(function (level) {
                                       console.log(level);
                                   });
                               }
                               // where I handle the click event
                               doStuff(el, this.text);
                               e.preventDefault();
                           })
                           .data('myName', result.name)
                           .data('myNumber', result.mynumber)
                           .text(result.name)
                   )
           );
  </code></pre>
  
  <p>Sample of data:</p>
  
  <pre><code>{
              "result_id": 7,
              "name": "My Name",
              "mynumber": "11",
              "levels": [
                  0,
                  1,
                  2
              ]
          }
  </code></pre>
  
  <p>Mockup</p>
  
  <p><a href="https://i.stack.imgur.com/WhxnQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WhxnQ.jpg" alt="enter image description here"></a></p>