Recursive walk through DOM elements strange behavior

Eleandro Duzentos
Eleandro Duzentos used Ask the Experts™
on
I'm trying to make a function that walks recursively through the elements bellow:

<body>
    <main class="main">
        <header class="e200-header">
            <a class="umburg side-item" href="#">
                <div>
                    <span class="line line-1"></span>
                    <span class="line line-2"></span>
                    <span class="line line-3"></span>
                </div>
            </a>
        </header>
        <section class="presentation">
        </section>
    </main>
</body>

Open in new window


This is the code that makes it:

function recursiveResolve(node) {
            if (typeof node != 'undefined') {
                //node.someMethod = aFunction

                var l = node.childElementCount

                if (l) {
                    childrens = node.children
    
                    for (var i = 0; i < l; i++) {
                        recursiveResolve(childrens[i])
                    }
                }
            }
        }

recursiveResolve(document.body)

Open in new window


The problem is that, its not working as expected, it is only resolving until the last <span class="line line-3"></span> and stops there when  <section class="presentation"></section> still remaining to be resolved. What i'm doing wrong?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
It's a problem with your variable scope. On line 8 you're setting a variable called childrens, but you're setting it as a global variable. Change the scope to a local variable and it'll work fine. Declare the variable with the var keyword:

var childrens = node.children;
Eleandro DuzentosWeb designer and software developer

Author

Commented:
Thats a little scope issue but because i'm learning it without follow any tutorial it becomes compplicated for me!

You saved my day!!! Thank you so  much!!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial