0

I have a tree view generated dynamically

the idea is to loop into them just to get the some values, but we don't know how many childs every element has.

<ul>
   <li>something here</li>
   <li>something here
        <ul>
           <li></li>
           <li></li>
            ...more and more childs
        </ul>
   </li>

</ul>
  • 1
    You should do it with a recursive function. – Evan Trimboli Nov 30 '16 at 00:40
  • 1
    Possible duplicate of [jQuery Find and List all LI elements within a UL within a specific DIV](http://stackoverflow.com/questions/7101945/jquery-find-and-list-all-li-elements-within-a-ul-within-a-specific-div) – John Wu Nov 30 '16 at 00:40
  • it would be much easier if you used attributes for the values – monssef Nov 30 '16 at 00:43

1 Answers1

2
function getNode($node) {
  var $children = $node.children();
  if ($children.length) {
    $children.each(function() {
        getNode($(this));
      })
      //Do something with the branch
  } else {
    //Do something with the leaf
  }
}

getNode($('#your_tree_top_node'));

This code will recursively go through your tree until it finds the leaves and allows you to act on the leaves first and then the branches after all the leaves of that branch has been processed.

DGS
  • 6,015
  • 1
  • 21
  • 37