title: How to dynamically create nested list using jQuery?
body: <p>I'm new to web development and I'm sort of stuck with this. I have the idea in mind but I don't know how to formulate it using jQuery. I have an unordered list which should be updated with a listitem every time a button is clicked. If a listitem is highlighted, then I click the Add button, it should create a sublist inside that li. Sample markup is: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
              $("#btnAdd").click(function () {
                  addExpression();
              });
  
              function addExpression() {
                  var mainList = document.getElementById("mainList");
                  var li = document.createElement("li");
                  var alink = document.createElement("a");
                  var str = document.createTextNode("test");
                  alink.appendChild(str);
                  li.appendChild(alink);
                  mainList.appendChild(li);
  
              }
  
              function createSublist() {
                  var sublist = document.createElement("ul");
                  var li = document.createElement("li");
                  var alink = document.createElement("a");
                  var str = document.createTextNode("test");
                  alink.appendChild(str);
                  li.appendChild(alink);
                  sublist.appendChild(li);
                  return sublist;
              }
  
              $(document).on("click", "ul.expression li", function () {
                  $("ul.expression li").removeClass("highlight");
                  $(this).addClass("highlight");
              });
  
          });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code> .expression ul {
              list-style: none;
          }
  
          .expression li {  
              width: 25%;
              height: 50px;   
              text-align: center;
              color: #B84DFF;
              cursor: pointer;
              border-style:solid;
              border-width:1px;
          }
  
          .expression li.highlight {
              background-color: cyan;
              font-weight: bold;
          }
          .hide {
              display: none;
          }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button id="btnAdd"&gt;Add&lt;/button&gt;
      &lt;div id="containerDiv"&gt;
          &lt;ul id="mainList" class="expression"&gt;
  
          &lt;/ul&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>My main problem is how to get the selected list item so that I can correctly insert a sublist inside it. Thanks in advance.</p>