Adding and Removing Nodes

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.

Node insertion methods (all but the last accept nodes and strings)
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
Building and editing a paragraphHTMLLive
<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>
Browser output of Listing 8.25
Browser output of 25

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