Scope problems in JavaScript recursion?

see an exercise on the Internet as follows:

<body>
    <div class="div1">
        <div class="div2">
            <div class="div3">
                <div class="div4"></div>
            </div>
        </div>
    </div>
    <script>
        function getNode(){
            var oDiv = document.getElementsByClassName("div4")[0];
            var parent = findNode(oDiv); 
            return parent;
        }
        function findNode(el){
            var rul = el.parentNode;
            
            if (!el || document.documentElement === rul || el === document.documentElement )
            {
                return;
            }else if (rul && rul.className === "div1")
            {
                return rul;
            }else {
                return findNode(rul);
            }
        }
        var s1 = getNode();
        console.log(s1.className);
    </script>
 </body>

Recursively finds the final parent of the child node. The above code can get a normal value; but if you put

return findNode(rul);return findNode(el);

will report an error: the maximum call stack size is exceeded
question: why is there an error?

Apr.08,2021

simplify it as follows, according to the way you write it. Can you see that? It's an infinite cycle! Recursion has a "depth" limit, and if it exceeds it, it will report an error: it exceeds the maximum call stack. In the V8 engine, this "depth" size is related to the stack and stack frames (local variables that hold parameters).

function findNode(el){
    return findNode(el);
}

in normal execution, el is the parameter of findNode and the element passed by the current
. The meaning of this function is to determine whether it is div1 or not. If not, recursively judge your parent element. If you change
to el, this function will recursively judge itself forever.

Recursion also requires a direction and an end condition.
"exceeding the maximum call stack size" actually means that the function is infinitely recursive. Because the parameters do not change during recursion

Menu