jquery - select parent node if all children have assigned class -


i looking efficient way traverse unordered list contains multiple levels contain class .selected. if ul li in group have class .selected, need add class .selected parent li of child ul.

<ul>     <li>one <-- li adds class .selected if children have .selected         <ul>             <li class="selected">red</li>             <li class="selected">green</li>             <li class="selected">blue</li>         </ul>     </li>     <li>two         <ul>             <li class="selected">red</li>             <li>green</li>             <li class="selected">blue</li>         </ul>     </li>     <li>three</li> </ul> 

if children in given ul have class .selected add class .selected parent li, in case li containing text "one" parent li have class .selected added.

i need happen when page loads. , have tried bunch of methods 1 came closest not sure if efficient:

$("ul li").filter(function () {     var lis_total = $(this).siblings().length + 1;     var lis_selected = $(".selected", this).siblings().length + 1;     if(lis_total == lis_selected)         return $(this).parent("li").addclass("selected"); }); 

i not sure if doing correctly. not working.

if want one-liner, try http://jsfiddle.net/4jnal/

$('li ul:not(:has(li:not(.selected)))').parent().addclass('selected'); 

or

var theparent = $('li ul:not(:has(li:not(.selected)))').parent(); 

to return element manipulation

for trees of arbitrary depth: http://jsfiddle.net/gqbmu/4/

do {     $results = $('li:not(.selected) > ul:not(:has(li:not(.selected)))');     $results.parent().addclass('selected'); } while ( $results.length > 0); 

or, since theme of answer one-liners: http://jsfiddle.net/gqbmu/6/

while ( $('li:not(.selected) > ul:not(:has(li:not(.selected)))').parent().addclass('selected').length > 0) {} ; 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -