Search code examples
jquerycssparentchildren

Add class to parents that have children using jquery


How would I go about adding a class only to the li parent that has children?

<ul>
    <li><a href="#">parent</a></li>
    <li><a href="#">parent</a>
    <ul>
        <li>child</li>
        <li>child</li>
    </ul>
</ul>

Solution

  • $('li > *').parent().addClass(...);
    

    or

    $('li').has('*').addClass(...);
    

    The first version may be marginally faster if you do:

    $('li > :first-child').parent().addClass(...);
    

    ...hard to say though without testing.

    All of these use fully valid CSS selectors.