0

This is my code:

var Tree = ( function ( _Obj ) {
  var _E,
      _N;
  _Obj.forEach ( function ( e ) {
    _E = document.createDocumentFragment();
    if ( "tagName" in e ) {
      _N = document.createElement( e.tagName ); 
    }
    if ( "childNode" in e ) {
      _N.appendChild( Tree ( e.childNode ) );
    }
  });
  _E.appendChild ( _N );
  return _E;
});

And here the parameter of that function:

Fragment = [{ // firstNode
    "tagName" : "div",
    "childNode" : [{
      "tagName" : "p",
      "childNode" : [{
        "tagName" : "string",
        "childNode" : [{
          "tagName" : "span",
        }]
      }]
    }]
  },
  { //secondNode
    "tagName" : "div",
    "childNode" : [{
      "tagName" : "p",
      "childNode" : [{
        "tagName" : "span",
        "childNode" : [{
          "tagName" : "div"
        }]
      }]
    }]
  }
];

This code should return a document fragment with EVERY object of the var Fragment. If you look, the JSON is based on a tagName and childNode elements; for each object depends on one tagName, so the function return one new element with the same name.

But something goes wrong here, the function only returns the SECOND NODE of the Fragment:

#document-fragment
|_<div>
  |_<p>
    |_<span>
        <div></div>
      </span>
    </p>
  </div>

That this is equal to:

{
    "tagName" : "div",
    "childNode" : [{
      "tagName" : "p",
      "childNode" : [{
        "tagName" : "span",
        "childNode" : [{
          "tagName" : "div"
        }]
      }]
    }]
  }

But, what happend with the FIRST NODE?

Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48

2 Answers2

1

Looks like your forEach loop goes through and assigns _N to the right stuff, but then only appends _N to _E after the entire loop has gone through. Move your _E.appendChild(_N) to the inside and bottom of your for each.

brazilianldsjaguar
  • 1,409
  • 1
  • 20
  • 45
0
var Tree = ( function ( _Obj ) {
  var _E,
      _N;
  _E = document.createDocumentFragment(); // put this out of forEach
  _Obj.forEach ( function ( e ) {
    if ( "tagName" in e ) {
      _N = document.createElement( e.tagName ); 
    }
    if ( "childNode" in e ) {
      _N.appendChild( Tree ( e.childNode ) );
    }
    _E.appendChild ( _N ); // put this inside of forEach
  });
  return _E;
});
xdazz
  • 158,678
  • 38
  • 247
  • 274