Find the deepest and the last li in any li blocks in a ul li list using jquery?

后端 未结 3 767
礼貌的吻别
礼貌的吻别 2021-01-15 14:07

I have a list in HTML. There are several nested ul and li.When I click on a li, I want to find a deepest item in that li tag that has no ul tag inside and the li is the last

3条回答
  •  走了就别回头了
    2021-01-15 14:18

    It looks like you are after the element which is last last item with the greatest depth (so if there are two items with equal depth but found in different ul's you want the last one). You could loop through all li's that don't have a ul and save the last one with the greatest quantity of parents. Once you've gone through everything just apply your CSS.

    $('.liclk').click(function() {
      var parentCount = 0;
      var $deepEl;
      $(this).find("li:not(:has(ul))").each(function(index, me) {
        if ($(me).parents().length >= parentCount) {
          parentCount = $(me).parents().length;
          $deepEl = me;
        }
      });
      $($deepEl).css("background-color", "red");
    });
    
    
    • I
    • II
      • A
      • B
        • 1
        • 2
        • 3
      • C
    • III
      • 4
      • 5
        • 5.1
        • 5.2
      • 5.3

提交回复
热议问题