Richard
Richard

Reputation: 1474

HTML list - Apply addClass() Only to First-Level LI Element (not Inner one)

I have the following code,

$('.main-menu li:nth-child(3)').addClass("active");

Which works, however, the HTML looks like this...

<ul>
    <li>menu item</li> 
    <li>menu item</li>
    <li>menu item       <!-- Target only this one! -->
        <ul>
            <li>menu item2</li>
            <li>menu item2</li>
            <li>menu item2</li> <!-- not this one -->
        </ul>
   </li>   
</ul>

And it adds the "active" class to both lists of LIs, any way to make it only add it once? Thank you

Upvotes: 1

Views: 829

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

http://api.jquery.com/child-selector/

Use the "immediate" child selector >

$('.main-menu > li:nth-child(3)').addClass("active");

http://jsbin.com/urekah/1/edit

Upvotes: 3

Related Questions