Rajib Hossen
Rajib Hossen

Reputation: 128

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

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 item of that groups. example follow this link for example

Here is my HTML code.

Here is my approach.

$('.liclk').click(function(){
    $(this).find("li").last().css( "background-color", "red" );
});

My solution is selecting last li but not the deepest.

I am beginner in jquery.

Upvotes: 2

Views: 1281

Answers (3)

John C
John C

Reputation: 3112

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");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="level-1">
  <li class="item-i liclk">I</li>
  <li class="item-ii liclk">II
    <ul class="level-1-1">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-1-1-1">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii liclk">III
    <ul class="level-2">
      <li class="item-4 ">4</li>
      <li class="=item-5 ">5
        <ul class="level-2-1">
          <li class="item-5-1">5.1</li>
          <li class="item-5-2">5.2</li>
        </ul>
        <li class="item-5-2">5.3</li>
      </li>
    </ul>
  </li>
</ul>

Upvotes: 0

George
George

Reputation: 36784

Use while to keep looking for a descending ul and when it can find no more, select the last list item within and apply CSS:

$('.liclk').click(function(){
    var $current = $(this).find('ul'),
        $desc = $current;
    while($desc.length){
        $current = $desc;
        $desc = $current.find('ul');
    }
    $current.find('li').last().css('background-color' ,'red')
});

JSFiddle

Upvotes: 5

An0nC0d3r
An0nC0d3r

Reputation: 1303

Something like this should do the trick...

    $('.liclk').click(function() {

        var el = $(this).find("ul:last-child").find('li:last-child').css("background-color", "red");
    });

Upvotes: 0

Related Questions