javascript - Move inside UL and change LI class if has .has_children class -
i need move inside ul element , change li , children ul class if .has_children
present. see example:
<ul class="nav navbar-nav"> <li class="first current parent">link1</li> <li class="parent">link2</li> <li class="has_children parent"><a href="#">link3</a> <ul class="dropdown"> <li class="first parent">subitem1</li> <li class="last parent">subitem2</li> </ul> </li> </ul>
here when found has_children
should change dropdown
in parent or root li. ul class dropdown
has has_children
parent should changed dropdown-menu dropdown-megamenu
. need iterative until latest nested level. result should this:
<ul class="nav navbar-nav"> <li class="active">link1</li> <li class="">link2</li> <li class="dropdown"><a href="#" data-close-others="true" data-hover="dropdown" data-toggle="dropdown" class="dropdown-toggle" >link3</a> <ul class="dropdown-menu dropdown-megamenu"> <li>subitem1</li> <li>subitem2</li> </ul> </li> </ul>
i tried code move inside elements:
$.each("ul.nav > li"), function(index, element) { console.log($(this).text()); }
but didn't work, can give me or push?
if have understood question correctly want change classnames, if case instead of using >
(child) selector can use descendant selector:
$("ul.nav li").each(function (index, element) { var $this = $(this), cls = ''; if ($this.hasclass('current')) { cls = 'active'; } else if ($this.hasclass('has_children')) { cls = 'dropdown'; $this.children('.dropdown') .attr('class', 'dropdown-menu dropdown-megamenu') .end() .children('a') .attr({ 'data-close-others': 'true', 'data-hover' : 'dropdown', 'data-toggle' : 'dropdown', 'class' : 'dropdown-toggle' }); } $this.attr('class', cls); });
please note have used attr
method resetting class attribute's value, if want add/remove classnames can use addclass
/removeclass
methods instead.
Comments
Post a Comment