Search code examples
javascriptxmlappendchildcreateelement

Piping createElement and appendChild in JavaScript


Can someone please explain to me, why

var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
Parent.appendChild(document.createElement("hi"));
Node.appendChild(Parent);

produces a different result from

var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
    .appendChild(document.createElement("hi"));
Node.appendChild(Parent);

In the second snippet the element testingOne doesn't even get included. Why does the piping do this?


Solution

  • Your first example will result in

    <testing><testingone><hi></hi></testingone></testing>
    

    Parent will contain the testingOne and the hi element will be appended to it.

    While the second example will result in

    <testing><hi></hi></testing>
    

    Because Parent will contain the hi element, which is returned by the appendChild method.