Search code examples
javascriptrecursionstack-overflow

javascript recursive function: Uncaught RangeError: Maximum call stack size exceeded


I have a recurent function that traverses a ul li nested hierarchy. It bubbles up from a certain node, until reaches the ul with class tree-0 (which is the root of the hierarchy).

The function:

function setupSelectedCategory(elem) {
    if (!elem)
        return;
    if (!elem.hasClass("tree-0")) {
        if (elem.parent().prop('tagName') == 'UL') {
            var index = jQuery(elem.parent().children()).index(jQuery(elem));
            jQuery(elem.parent()).accordion({ active: index });
        }
        return setupSelectedCategory(jQuery(elem.parent()));
    } 
    return;
}

THE PROBLEM:

I've got a stack overflow exception (at least in chrome). Maybe i'm not exiting the right way from the function? Have some ideas?


Solution

  • The check is faulty.. do

    if( !elem || !elem.size() )