Level: Intermediate | Player: 17_DOM_Selection and_View
Learning Objectives
- Change the tree to
createElement,appendChild,prepend, andremove. - Change the class to
classListas Add/Remove/Toggle. - Change the inline style with the
styleproperty. - Efficiently insert multiple nodes into DocumentFragment.
- Set text and properties safely.
1. Creating and adding elements
const li = document.createElement("li");
li.textContent = "new item";
list.appendChild(li);
append can receive multiple nodes and strings at once. prepend is added in front.
2. Remove
target.remove();
parent.removeChild(target); //old fashioned
3. classList
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");
el.classList.contains("active");
Be careful because className = "..." overwrites all existing classes.
4. style
el.style.color = "red";
el.style.backgroundColor = "yellow";
background-color in CSS becomes backgroundColor in camel case in JavaScript.
5. DocumentFragment
Use fragment to reduce reflow when inserting many nodes at once.
const frag = document.createDocumentFragment();
for (let i = 0; i < 100; i += 1) {
const li = document.createElement("li");
li.textContent = `item ${i}`;
frag.appendChild(li);
}
list.appendChild(frag);
Core example
| file | Contents covered |
|---|---|
| index.html | Example HTML |
| 01_create_element.js | createElement + appendChild |
| 02_append_remove.js | append/prepend/remove |
| 03_classlist.js | classList add/remove/toggle |
| 04_style.js | style property settings |
⚠️ Common Mistakes
- Pass a string to
appendChild(nodes only, append is possible). - Decreased performance by adding to the parent every time within a loop.
- Delete the existing class with
className = "x". - Missing style unit (
px, etc.). - AppendChild → Only moves the same node to two places (not duplicates).
❓ Frequently Asked Questions (FAQ)
Q1. Difference between appendChild and append? A. append receives multiple node/string and has no return value. appendChild returns only one node, the added node.
Q2. Why is classList better? A. It can be safely manipulated without affecting other classes.
Q3. Should I use inline style or CSS class? A. If possible, use class toggle, and only dynamic calculated values (e.g. coordinates) inline style.