How do you build a DOM subtree in JavaScript?
You create the elements, you set them up, you attach the children to their parents, and only then do you attach the whole thing to the document. That order is what makes it fast, because the browser does no layout work for a node until the node is actually on the page.
// A tiny stand-in for the browser DOM, so this example runs in Node.
function element(tag, attributes) {
if (!attributes) {
attributes = {};
}
return {
tagName: tag.toUpperCase(),
attributes: attributes,
children: [],
setText(value) {
this.text = value;
return this;
},
appendChild(child) {
this.children.push(child);
return child;
},
};
}
const list = element('ul', { class: 'topics' });
const topics = ['Closures', 'Promises', 'Prototypes'];
for (let index = 0; index < topics.length; index++) {
const item = element('li');
item.setText(topics[index]);
list.appendChild(item);
}
console.log(list.tagName); // UL
console.log(list.attributes.class); // topics
console.log(list.children.length); // 3
Two variations of the loop are worth knowing. You can build the string of markup first and assign it with innerHTML in one operation. That is faster for a large amount of fixed content, but it loses any event listeners and it is only safe when you trust the markup. The other option is to build a document fragment, which is a container that lives outside the document, and then attach the finished result in one call.
Another detail is worth raising. The appendChild method moves a node instead of copying it. If the node is already somewhere in the document, appending it somewhere else takes it away from its old position. That is exactly what you want when you are rearranging a list, and it is a bug when you assumed that you were making a copy.
There is also a note about text. Use the textContent property to set the text of a node, and keep innerHTML for markup that you built yourself. A string that a user typed and that you paste into innerHTML is the classic cross-site scripting bug.