简体   繁体   中英

Jquery: How to target the parent ul and count the li's held?

I am using jstree to build a tree menu.
When you select an item in the tree a div on the right brings up certain information. The information can be deleted.
When it is deleted I remove that item from the tree.
The problem is when the last li is removed from the ul, I need to remove the ul and also remove the "open" and "close" classes from the parent li and add the class "leaf".
I am having a hard time targeting the ul and in turn targeting the parent li as well. I have to use the "clicked" class as a starting reference.

Here is the tree html:

<li id="447" class="open">
     <a href="#"><ins>&nbsp;</ins>ZigBee Remote Pairing-D</a>
     <ul>
         <li id="470" class="leaf last clicked">
               <a href="#"><ins>&nbsp;</ins>RCA TV2 - Audio Quality-F</a>
         </li>
     </ul>
 </li>

here is the jquery:

var numLi = $(".clicked").parent("ul:first > li").size();//get number of li in ul             
if (numLi == 1){
    $(".clicked").parent("ul:first").parent("li:first").removeClass().addClass("leaf");
}
$(".clicked").parent("li:first").remove();//remove the list item from the tree

Something like this should work:

var clickedLi = $('.clicked').parent('li');
var parentUlOfClickedLi = clickedLi.parent('ul');
if (parentUlOfClickedLi.children('li').length === 1) {
    parentUlOfClickedLi.parent('li')
        .removeClass('open close')
        .addClass('leaf');
}
clickedLi.remove();

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