Arvin
Arvin

Reputation: 13

Why this DOM DFS algorithm doesn't work?

I tried the algorith below to DFS the DOM tree but it doesn't work! It can just check the first path in the DOM tree. WHY?!

function DFS(P) // (ScanRegion, Elem, MCF)
{
    P.Elem.setAttribute("Checked", "1");

    Children = P.Elem.querySelectorAll("*");

    for(I = 0, L = Children.length; I < L; I++)
        DFS
        (
            {
                ScanRegion : P.ScanRegion,
                Elem       : Children[I] ,
                MCF        : P.MCF
            }
        );

    return;
}

DFS
(
    {
        ScanRegion : document.body,
        Elem       : document.body,
        MCF        : "Not important in this question :D"
    }
);

after days of debugging I finally found out the problem. I tried the code below and understood that after the function riches to the first leaf of the DOM tree and the browser runs the first 'return' of the recursive function, the 'L' variable of the parent function loses its value and changes to '0'. I guess that it is because of variable scope problems in JS because as you know the 'L' of the child function is '0' (Because a leaf has no child :D) and I think it affects on the parent function.

here's the debugging code I tried:

function DFS(P) // (ScanRegion, Elem, MCF)
{
    P.Elem.setAttribute("Checked", "1");

    Children = P.Elem.querySelectorAll("*");

    L = Children.length; alert(L); // * New

    for(I = 0; I < L; I++)
        DFS
        (
            {
                ScanRegion : P.ScanRegion,
                Elem       : Children[I] ,
                MCF        : P.MCF
            }
        );

    alert(L); // * New

    return;
}

DFS
(
    {
        ScanRegion : document.body,
        Elem       : document.body,
        MCF        : "Not important in this question :D"
    }
);

I would be grateful if any one knows the problem or has the true code :)

Upvotes: 1

Views: 175

Answers (1)

Pointy
Pointy

Reputation: 413709

Declare your local variables with var!! As it stands, I is global. Same with L. Because of that, the recursive calls mess up the parent's iteration.

Add

var I, L;

to the top of the function. (Also consider using lower-case for variable names; it's much more common in JavaScript code.)

Upvotes: 1

Related Questions