freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #5 of 21

creating elements · createElement · appendChild

NodetteVSThe Event Bubbler
Nodette saysCreate elements with createElement and insert them with append/prepend/before.

document.createElement("div") makes a detached element; set its content/attributes, then insert with parent.append(el), prepend, before, or after. For many inserts at once, build a DocumentFragment and append it once — far fewer reflows than inserting one at a time.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleCreate 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
‹ Traversal · ParentNode · Children · SiblingsRemoving Elements · Remove · RemoveChild ›