jquery selecting all last elements of an nested tree menu unordered list...not just the :last-child
I'm having some trouble figuring this out. I have an unordered list menu that I want to style all the last elements with a folder icon and style all the expandable (parent) elements with a plus.gif image. I wanted to simply change the class by using .addclass() using jquery, which will contain the css to add the background-image. My jquery code below is only selecting the ":last-child", which is placing a folder icon on the last element in the list. i need to place a folder icon in front of all the "li's" that don't hav any children, and place a plus icon in front of all those that do have children. Is there a way to accomplish this?
Here's my HTML:
<ul id="nav">
<li>Heading 1
<ul>
<li>Sub page A
<ul>
<li>Sub page A - 1
<ul>
<li>A - 1: 0</li>
<li>A - 1: 1</li>
<li>A - 1: 2</li>
</ul>
</li>
<li&开发者_StackOverflowgt;Sub page A - 3</li>
<li>Sub page A - 2</li>
</ul>
</li>
<li>Sub page B</li>
<li>Sub page C
<ul>
<li>Sub page C - 1
<ul>
<li>C - 1: 0</li>
<li>C - 1: 1</li>
<li>C - 1: 2</li>
</ul>
</li>
<li>Sub page C - 3</li>
<li>Sub page C - 2</li>
</ul>
</li>
</ul>
</li>
<li>Heading 2
<ul>
<li>Sub page D</li>
<li>Sub page E</li>
<li>Sub page F</li>
</ul>
</li>
<li>Heading 3
<ul>
<li>Sub page G</li>
<li>Sub page H</li>
<li>Sub page I</li>
</ul>
</li>
</ul>
Here's the jquery code:
$(function(){
//add class to last item in each list
$('#nav li').find('li:last').addClass('menu_last_child');
});
This will add your class to all li
's that do not have children
$("#nav li:not(:has(li))").addClass('menu_last_child');
This will add a class to all li
's that DO have children
$("#nav li:has(li)").addClass("menu_parent");
Also keep in mind that there is a difference between :last
and :last-child
. The former will select only the last item in the returned set of items matching the selector, while the latter will return all items that are the last in the context of their parent (same as css :last-child
selector)
精彩评论