Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the leaf count for each parent ul in a nested ul structure

Given a html structure that looks like the following html, but is of arbitrary depth. (i.e. it could go many levels deeper). Because it is of arbitray depth, I would prefer a solution that doesn't require adding any extra markup to the html (e.g. classes)

<ul><!-- Leaf Count 3 -->
  <li>branch 1
    <ul><!-- Leaf Count 2 -->
      <li>leaf 1</li>
      <li>leaf 2</li>
    </ul>
  </li>
  <li>leaf 3</li>
</ul>

How can I count all the leaves that are a child of each ul? So in this example the outer most ul would have 3 leaves and the nested one two leaves. This seems like a recursion issue, but I can't think through it.

like image 381
Hopeless Avatar asked Jun 28 '17 06:06

Hopeless


1 Answers

I think accepted answer is not more efficient. There is even simpler way of doing this.

We can use jquery simple selectee li:not(:has(*)). This will find all li element that doesn't have children(leaf node).

Use $("#dvMain").find('ul').each which will find all ul element and then loop through it.

$(document).ready(function() {
    $("#dvMain").find('ul').each(function(item) {
        console.log($(this).find('li:not(:has(*))').length);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="dvMain">
<ul><!-- Leaf Count 4 -->
  <li>branch 1
    <ul><!-- Leaf Count 2 -->
      <li>leaf 1</li>
      <li>leaf 2</li>
    </ul>
  </li>
  <li>branch 1
    <ul><!-- Leaf Count 1 -->
      <li>leaf 1</li>
    </ul>
  </li>
  <li>leaf 3</li>
</ul>
</div>
like image 75
Mayur Patel Avatar answered Sep 30 '22 13:09

Mayur Patel