javascript - Find nested order of ul's and add specific classes -


i trying figure out way loop through container

<nav id="container">   <ul>     <li>text</li>     <li>       <ul>         <li>text</li>         <li>           <ul>             <!-- , on -->           </ul>        </li>       </ul>     <li>   </ul> </nav> 

and check how deep ul nested in if first 1 add class="level-1" it, if second .level-2 etc. bear in mind, each <ul> can contain more 1 nested ul (multi level navigation).

demo

simply iterate through uls , create classname based on how many parent uls each has, using parentsuntil() in case #container within ul.

$(function(){     $('#container ul').each(function(){         var classname = 'level-' + ($(this).parentsuntil('#container', 'ul').length + 1);         $(this).addclass(classname);     }); }); 

a shorter way write (courtesy of arun p johny) is

$('#container ul').addclass(function(){     return 'level-' + ($(this).parentsuntil('#container', 'ul').length + 1); }); 


included css tag. if purely css, can use css. see http://jsfiddle.net/a9jrd8sn/4/


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -