Hide the tree menu at a certain depth
It would be much easier just to let the CSS selector engine select the elements to hide:

var hideDepth = function(root, depth) {
   root.find('ul').show(); // Make sure all sublists are visible 
   var selector = Array(depth + 1).join(' &gt; li &gt; ul'); // Repeat string
   root.find(selector).hide();
}

var depth = 2; 
var selectedUL = $("#tree");

hideDepth(selectedUL, depth);


NOTE: Add the id tree to the top level ul. Your selector $('ul')selects all lists in the document, not just the top one, so your code was unnecessarily called repeatedly for each sub list.

For the string repeating see: https://stackoverflow.com/questions/1877475/repeat-character-n-times.