check an element if exists and add class to its previous element and to it with jquery

check an element if exists and add class to its previous element and to it with jquery

I have a vertical menu code, and i want to add collapsable sub menus,
here is structure of my Menu's HTML code:

  1.     <div class="menu">
  2. <ul>
  3.  <li><a>1</a></li>
  4. <li><a>2</a></li>
  5. <li><a>3</a>
  6.   <ul>
  7.       <li><a>sub1</a></li>
  8.    </ul>
  9.  </li>
  10. </ul>
  11.       </div>


so as you can see here, many of the li tags of .menu > ul are there but only some would have sub menus in them.

i tried to create jquery which could add treeview class to the li tag which contains the sub menu's ul tags and treeview-sub to the sub menu's ul but failed (only treeview-sub able to be added correctly, but not able to successfully add .treeview class to its li).

Edit: And when user Click the li tag then it should copy li's "a" tag content and append it to its child ul.. but looks like its not happening.

Here is the jquery code:

  1.     if($(".menu > ul > li > ul")){
  2.     $(".menu > ul > li > ul").addClass("treeview-sub");
  3.     $(".menu").on('click', 'ul > li', function(e) {
  4.     var $this = $(this);
  5.     if($(this).children("ul")) {
  6.     var $li_a = $this.children("a");
  7.     $html_overview = ($li_a).html();
  8.     $(this).children("ul").append($html_overview);
  9.     $(this).addClass("treeview");
  10.     };
  11.     })
  12.     }
so here it should change the above HTML to something like below:

  1.     <div class="menu"> <ul> <li><a>1</a></li><li><a>2</a></li><li class="treeview"><a>3</a><ul class="treeview-sub"><li><a>sub1</a></li></ul></li</ul></div>

and when we click on li > .treeview then it should append all html of li > .treeview > a to li > .treeview > ul (after click it should look like this):

  1.     <div class="menu"> <ul> <li><a>1</a></li><li><a>2</a></li><li class="treeview"><a>3</a><ul class="treeview-sub"><li><a>3</a></li><li><a>sub1</a></li></ul></li</ul></div>

and when click again then it should remove the extra li tag which we had append in its submenu