javascript - How to wrap groups of li tags inside ul -
i have navigation menu contains bunch of li tags , of them having class "sub-item" , want group li tags inside ul navigation :
<ul class='main-menu'> <li><a href="#">home</a></li> <li><a href="#">pages</a></li> <li class='sub-item'><a href="#">_contact us</a></li> <li class='sub-item'><a href="#">_community</a></li> <li class='sub-item'><a href="#">_about me</a></li> <li class='sub-item'><a href="#">_blog</a></li> <li><a href="#">dropdown </a></li> <li class='sub-item'><a href="#">_sub menu 1</a></li> <li class='sub-item'><a href="#">_sub menu 2</a></li> <li class='sub-item'><a href="#">_sub menu 3</a></li> <li class='sub-item'><a href="#">_sub menu 4</a></li> <li><a href="#">sign out</a></li> </ul>
will become :
<ul id='main-menu'> <li><a href="#">home</a></li> <li><a href="#">pages</a></li> <ul class="sub-menu"> <li class='sub-item'><a href="#">_contact us</a></li> <li class='sub-item'><a href="#">_community</a></li> <li class='sub-item'><a href="#">_about me</a></li> <li class='sub-item'><a href="#">_blog</a></li> </ul> <li><a href="#">dropdown </a></li> <ul class="sub-menu"> <li class='sub-item'><a href="#">_sub menu 1</a></li> <li class='sub-item'><a href="#">_sub menu 2</a></li> <li class='sub-item'><a href="#">_sub menu 3</a></li> <li class='sub-item'><a href="#">_sub menu 4</a></li> </ul> <li><a href="#">sign out</a></li> </ul>
this attempt unfortunately didn't worked :
$('.main-menu li a').each(function() { var $this = $(this), content = $this.text(); if (content.indexof('_') != -1) { $this.parent('li').addclass('sub-item'); } }); $('.sub-item').wrapall('<ul class="sub-menu"></ul>');
here jsfiddle demo : http://jsfiddle.net/hc05fhxr/1/
the desired output given in question invalid li can't have ul
content.
i possible alternate add new ul
descendant of previous anchor
$('li:not(.sub-item)').each(function() { var $li = $(this), $subs = $li.nextuntil(':not(.sub-item)'); if ($subs.length) { $('<ul />', { 'class': 'sub-menu' }).html($subs).appendto($li); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class='main-menu'> <li><a href="#">home</a></li> <li><a href="#">pages</a></li> <li class='sub-item'><a href="#">contact us</a></li> <li class='sub-item'><a href="#">community</a></li> <li class='sub-item'><a href="#">about me</a></li> <li class='sub-item'><a href="#">blog</a></li> <li><a href="#">dropdown </a></li> <li class='sub-item'><a href="#">sub menu 1</a></li> <li class='sub-item'><a href="#">sub menu 2</a></li> <li class='sub-item'><a href="#">sub menu 3</a></li> <li class='sub-item'><a href="#">sub menu 4</a></li> <li><a href="#">sign out</a></li> </ul>
Comments
Post a Comment