5
\$\begingroup\$

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);
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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(' > li > 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.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.