Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to create and nest divs with appendChild using *plain* javascript (no libraries)

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");
like image 926
Matrym Avatar asked Jan 23 '23 05:01

Matrym


2 Answers

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:

var d = document;
var docBody = d.getElementsByTagName("body")[0];
    
// Copyier dom
var sasDom = d.createElement('span');
sasDom.setAttribute("id", "sasText");

// Hider dom
var sasDomHider = d.createElement('span');
sasDomHider.setAttribute("id", "sasHider");

sasDomHider.appendChild(sasDom); // append child to parent
docBody.appendChild(sasDomHider); // ...and parent to DOM body element

Original answer:

You're trying to insert the same element twice, in the same spot...

var newNode = d.createElement('span');

...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:

docBody.appendChild(newNode);

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:

newNode = d.createElement('span');
newNode.setAttribute("id", "sasText");
sasDomHider.appendChild(newNode);
// the next line is unnecessary; we already have an element reference in newNode
// sasDom = d.getElementById("sasText");
// ... so just use that:
sasDom = newNode;
like image 94
Shog9 Avatar answered Feb 06 '23 16:02

Shog9


You don't need to search again for the nodes:

var d = document;
var docBody = d.body;
var sasDomHider = d.createElement('span');
var sasDom = d.createElement('span');

// Hider dom
sasDomHider.setAttribute("id", "sasHider");
docBody.appendChild(sasDomHider);

// Copyier dom
sasDom.setAttribute("id", "sasText");
sasDomHider.appendChild(sasDom);
like image 29
AlfonsoML Avatar answered Feb 06 '23 16:02

AlfonsoML