i’m working on styling my site’s main menu and i would like to add a class to the first and last LI elements in the unordered list, but only the first and last items in the top level.
<div id="primary-menu-container" class="menu">
<div id="menu-icon">Menu</div>
<ul id="primary-menu" class="hover sf-menu">
<li><a href="#">Fabrics</a></li>
<li><a href="#">Contemporary</a></li>
<li><a href="#>Vinyl</a></li>
<li><a href="#">Gold</a></li>
<li><a href="#">History</a></li>
<li><a href="#">Test Tag</a>
<ul class="sub-menu">
<li><a href="#">Testing</a></li>
<li><a href="#">news</a></li>
</ul>
</li>
</ul>
</div>
the first one is pretty easy since the first li is always a top-level list element. i’m confused about targeting the last one since there could be a sub-menu on the last top-level list element.
there was no solution selected, but per some of the responses at : how to add class into last li of first level
i’ve tried the following, which works on the first item, but adds the “last” class to “Test Tag” and all its children, whereas I only want this class added to the “Test Tag” li.
$("#primary-menu > li:first").addClass("first");
$("#primary-menu > li:last").addClass("last");
here’s my fiddle.
Fixed: http://jsfiddle.net/tdcf7/3/
It was not adding the class to all descendants; your CSS selector (
.last a) was just selecting all descendants of the single item with the class.By using the child selector instead of descendant, the fix above only selects the
<a>that is directly a child of the<li>with that class.Alternatively–if it is hard to select exactly just the contents you want–you can always apply styling to all descendants and then override it for the incorrect ones: