freecoding.school100% FREE · NO SIGNUP
The Old NetISSUE #36 of 60

inserting nodes · appendChild · insertBefore

Pixel PeteVSQuirks Mode
Pixel Pete saysInsert nodes with append/appendChild, prepend, insertBefore, before/after.

parent.append(node) adds to the end (modern, accepts text and multiple nodes); appendChild is the older single-node version. prepend adds to the start, before/after insert as siblings, and insertBefore(new, ref) places before a reference child. For many inserts, build a DocumentFragment and append once to minimize reflow.

Power-ups you unlock

Quirks Mode attacks — common mistakes

Boss battleBuild three list items in a fragment and append them in one operation.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;padding:20px"><ul id="l"></ul>
<script>const f=document.createDocumentFragment();['x','y','z'].forEach(t=>{const li=document.createElement('li');li.textContent=t;f.append(li);});document.getElementById('l').append(f);</script></body></html>
▶ Open the interactive comic issue
‹ CreateElement · CreateTextNodeRemoving Nodes · RemoveChild ›