简体   繁体   中英

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>
$('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.

$('li:has(ul)').addClass('test-class');

I love how simple jQuery makes some things.

Here is jsfiddle of the above code: http://jsfiddle.net/p9M73/

Here is the documentation for :has() : http://api.jquery.com/has-selector/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM