Jquery, selecting all the last elements of an unordered list of a nested tree ... not only: last-child

I am having trouble with this. I have an unordered list menu in which I want to stylize all the last items with a folder icon and stylize all expandable (parent) items with plus.gif image. I wanted to just change the class using .addclass (), using jquery, which will contain css to add the background image. In the jquery code below, you select ": last-child", which places the folder icon in the last item in the list. I need to put a folder icon in front of all the "whether" that have no children, and put a plus sign in front of all those who have children. Is there any way to do this?

Here is 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>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'); }); 
+4
source share
1 answer

This will add your class to all li that don't have children

 $("#nav li:not(:has(li))").addClass('menu_last_child'); 

This will add a class to all li that 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 element in the returned set of elements matching the selector, while the latter will return all elements that are the last in the context of their parent element (same as the css :last-child selector)

+4
source

Source: https://habr.com/ru/post/1304943/


All Articles