add class to li if it has child ul

13,829

Solution 1

Try this and use just one $(selector):

$('ul li:has(ul)').addClass('hassub');

Live DEMO:

http://jsfiddle.net/oscarj24/fNrQE/2/

Solution 2

Try .has

$('ul li').has('ul').addClass('hassub');

Solution 3

You don't need to check if the ul exists to add class to parent li, you can just target the child ul in the jQuery selector. Here is an example:

// Add Class to LI with Child UL (Level 1)
$('.menuDiv li ul').parent().addClass('hasChild');

If the ul is not found, the code will not trigger. After you added the class to all list items, you can simply target only the first child anchor (if you want) using the > selector:

.menuDiv li.hasChild > a

... or target all the <ul> with the li parent class:

.menuDiv li.hasChild ul

You can check the link below to see live examples (also with level 2 lists) and more details about the code:

http://html-tuts.com/add-class-to-parent-li-if-has-child-ul/

Share:
13,829
ak85
Author by

ak85

mainly a frontend developer trying to learn more about php and mysql SOreadytohelp

Updated on November 22, 2022

Comments

  • ak85
    ak85 over 1 year

    I have a menu item that looks like this.

    <ul>
    <li><a href="id=1">HOME</a></li>
    <li><a href="id=2">News</a>
        <ul>
            <li><a href="id=3">News Archive</a></li>
        </ul>
    </li>
    </ul>
    

    I want it to look like this

    <ul>
    <li><a href="id=1">HOME</a></li>
    <li class="hassub"><a href="id=2">News</a>
        <ul>
            <li><a href="id=3">News Archive</a></li>
        </ul>
    </li>
    </ul>
    

    So that if the li has a child then it will have a class of hassub.

    I have tried adding this with jQuery, see fiddle. But it is adding the class to all ul li. Where am I going wrong?