We help IT Professionals succeed at work.

Recursive walk through DOM elements strange behavior

Eleandro Duzentos
Eleandro Duzentos asked
I'm trying to make a function that walks recursively through the elements bellow:

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

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++) {


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?
Watch Question

Most Valuable Expert 2018
Distinguished Expert 2018
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


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!!!