Is there a more efficient way to write the following appendChild / nesting code?
var sasDom, sasDomHider;
var d = document;
var docBody = d.getElementsByTagName("body")[0];
var newNode = d.createElement('span');
var secondNode = d.createElement('span');
// Hider dom
newNode.setAttribute("id", "sasHider");
docBody.appendChild(newNode);
sasDomHider = d.getElementById("sasHider");
// Copyier dom
secondNode.setAttribute("id", "sasText");
sasDomHider.appendChild(secondNode);
sasDom = d.getElementById("sasText");
Ok, question has changed. Blah. Here’s the new answer:
You might gain a little bit in the way of execution efficiency by building the branch before appending it to the DOM tree (browser won’t try to recalc anything while building). And a bit in the way of maintenance efficiency by reducing the number of superfluous variables:
Original answer:
You’re trying to insert the same element twice, in the same spot…
…That’s the only place you’re creating an element in this code. So there’s only one element created. And you insert it after the last child element in the body here:
So far, so good. But then, you modify an attribute, and try to insert the same node again, after the last child of sasDomHider… which is itself! Naturally, you cannot make a node its own child.
Really, you want to just create a new element and work with that: