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:
- <div class="menu">
- <ul>
- <li><a>1</a></li>
- <li><a>2</a></li>
- <li><a>3</a>
- <ul>
- <li><a>sub1</a></li>
- </ul>
- </li>
- </ul>
- </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:
- if($(".menu > ul > li > ul")){
- $(".menu > ul > li > ul").addClass("treeview-sub");
- $(".menu").on('click', 'ul > li', function(e) {
- var $this = $(this);
- if($(this).children("ul")) {
- var $li_a = $this.children("a");
- $html_overview = ($li_a).html();
- $(this).children("ul").append($html_overview);
- $(this).addClass("treeview");
- };
- })
- }
so here it should change the above HTML to something like below:
- <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):
- <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