I have created this piece of js purely for learning purposes and I was hoping you could code review to see any mistakes / improvements I can make.
Basically I have a tree structure and I will use the depth variable to work out what level of the menu I will display.
Here is the code example: http://jsfiddle.net/nqGbw/5/
HTML
The Tree
<ul>
<li> <a href="?1">Root</a>
<ul>
<li> <a href="?2">Folder 1</a>
<ul>
<li><a href="?3">Folder 1.1</a>
</li>
<li><a href="?4">Folder 1.2</a>
</li>
</ul>
</li>
<li> <a href="?5">Folder 2</a>
<ul>
<li><a href="?6">Folder 2.1</a>
</li>
<li> <a href="?7">Folder 2.2</a>
<ul>
<li><a href="?8">Folder 2.2.1</a>
</li>
<li><a href="?8">Folder 2.2.2</a>
</li>
<li><a href="?9">Folder 2.2.3</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
JS
var calcDepth = function (root) {
var $parent = $(root).parents('ul');
var depth = 0;
while ($parent.length > 0) {
$parent = $parent.parents('ul');
depth += 1;
}
return depth;
};
var func = function (rootUL, maxDepth) {
var selectedUL = rootUL;
$(selectedUL.children('li')).each(function () {
var Me = $(this);
if (calcDepth(Me.parent()) == maxDepth) {
Me.hide();
}
if (Me.children('ul').length > 0) {
var selectedUL = Me.children('ul');
func(selectedUL, maxDepth);
}
});
};
var depth = 2; //Change this to set the depth of the menu
var selectedUL = $("ul");
func(selectedUL, depth);