Create nodes with document.createElement() and place them with the methods below; inserting a node that is already in the tree moves it. The classic appendChild(), insertBefore() and removeChild() still work but take a single node.
| Method | Called on | Effect |
|---|---|---|
| append(), prepend() | Parent | Add after last / before first child |
| before(), after() | Child | Add before / after itself |
| replaceWith(), remove() | Child | Replace / remove itself |
| insertAdjacentHTML(pos, html) | Element | Parse HTML at pos |
<pre id="out" style="margin:0"></pre>
<script>
const [box, p, i] = ['div', 'p', 'i'].map((tag) => document.createElement(tag));
i.textContent = 'world';
p.append('Hello ', i); // strings become text nodes
box.append(p);
p.insertAdjacentHTML('afterend', '<p id="p2">How do you do?</p>');
i.replaceWith('Worldie'); // i is now detached
p.after('!');
p.prepend(i); // reuse the detached node
box.querySelector('#p2').remove();
document.querySelector('#out').textContent = box.innerHTML;
</script>
pos is beforebegin, afterbegin, beforeend or afterend. insertAdjacentHTML() keeps existing children, so it replaces innerHTML +=, though it is still an injection sink. For many nodes, fill a DocumentFragment and insert once (Delegation and Batching).