Search code examples
jqueryhtmlcsscontent-management-systemmarkup

Add class to each level of ul li using jQuery


I have this nested ul, which are parent -> child -> (grand)child levels.

How can I use jQuery to spot every level adding a class to it so that I can style each level differently?

would be something like:

enter image description here

I couldn't do it with CSS because it needs to work fine at least on IE 7

<ul class="lista-regioes">
    <li class="cat-item cat-item-3 i-have-kids">
     <a href="http://localhost/poraidemochila/site/?local-destino=brasil" title="Ver todos os posts arquivados em Brasil">Brasil</a>
     <ul class="children">
        <li class="cat-item cat-item-13">
        <a href="#" title="#">Norte</a>
        </li>
        <li class="cat-item cat-item-4 i-have-kids">
        <a href="#" title="#">Sul</a>
        <ul class="children">
            <li class="cat-item cat-item-5">
                <a href="http://localhost/poraidemochila/site/?local-destino=parana" title="Ver todos os posts arquivados em Paraná">Paraná</a>
            </li>
        </ul>
    </li>
</ul>
    </li>
</ul>

the classes .cat-item and .cat-item-# are dynamically generated, so I can't use them in css the class .i-have-kids is added by the following js which I found here

 $('li.cat-item:has(ul.children)').addClass('i-have-kids');

but it does not really work since it just looks for elements that have children, and do not separate by levels, as you can see in the markup.


Solution

  • Why not just do something like this: http://jsfiddle.net/Rpg88/

    HTML

    <ul>
        <li><a href="#">link</a></li>
        <li>
            <a href="#">link</a>
            <ul>
                <li><a href="#">link</a></li>
                <li>
                    <a href="#">link</a>
                    <ul>
                        <li><a href="#">link</a></li>
                        <li><a href="#">link</a></li>
                        <li><a href="#">link</a></li>
                    </ul>
                </li>
                <li><a href="#">link</a></li>
            </ul>
        </li>
        <li><a href="#">link</a></li>
    </ul>
    

    CSS

    ul a { color:red; }
    ul ul a {color:orange;}
    ul ul ul a {color:lime;}