0

I don't understand why this fails:

var recursiveElementGenerator = function (elem_spec) {
    elem = document.createElement(elem_spec.tag);

    if (elem_spec.children) {
        for (var i=0; i<elem_spec.children.length; i++) {
            var c_elem = elem_spec.children[i];
            var n_elem = recursiveElementGenerator(c_elem);
            alert(elem===n_elem);
            elem.appendChild(n_elem);
        };
    };
    return elem;
};

The elem_spec object has tag and children attributes, the latter being an array of similar objects.

This fails because the element returned by the recursive call is the same as the element created before that recursive call. Which I don't get -- a similar version works, by getting its chain of tag values from a pop() call on an array that is then passed into the recursive call.

1
  • I would take a look at the elem_spec argument. Can you post a sample of that? Commented Mar 17, 2011 at 1:03

1 Answer 1

2

Try using:

var elem = document.createElement(elem_spec.tag);

instead of:

elem = document.createElement(elem_spec.tag);

Not using the var keyword makes your variable operate on the global scope. Using it will create the variable in the local scope, from the line it's created to the end of your function definition.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 good catch! The global variable has been used in the recursive calls. That is why n_elem always point to the same object as the elem global variable.
Yep, that's a d'oh moment -- thanks -- I tried to upvote / accept this morning but stackoverflow was in some glitch moment that wouldn't take my inputs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.