HTML•Dynamic Elements
Dynamic DOM: document.createElement and appendChild
Learn programmatic DOM generation: instantiate elements, configure attributes, and insert into the DOM.
Syntax
const li = document.createElement("li");
li.textContent = "Item";
ul.append(li);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| document.createElement() | Method | Creates specified HTML element node. |
| append() | Method | Appends element node or string to container. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing HTML locally:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; padding: 20px; }
ul { list-style: none; padding: 0; }
li { background: #f8fafc; border: 1px solid #e2e8f0; padding: 10px; margin-bottom: 6px; border-radius: 6px; }
button { background: #0284c7; color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; }
</style>
</head>
<body>
<h2>Dynamic Task List</h2>
<button id="add-btn">+ Add Server Node</button>
<ul id="node-list"></ul>
<script>
let nodeIndex = 1;
const addBtn = document.querySelector("#add-btn");
const nodeList = document.querySelector("#node-list");
addBtn.addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = "Node-" + nodeIndex++ + " (Healthy, Port " + (8000 + nodeIndex) + ")";
nodeList.append(li);
});
</script>
</body>
</html>Expected Output:
[Interactive UI: Clicking "+ Add Server Node" Creates and Injects New List Items Dynamically]
How It Works: Step-by-Step
- Lines 21-24: Creates <li> element, sets textContent, and appends to #node-list.
Key Concepts
- createElement creates an in-memory element not yet attached to the page.
- Calling container.append(el) mounts the element into the visible document tree.
Common Mistake: Re-rendering the entire list using innerHTML += inside loops
Writing list.innerHTML += "<li>..." destroys all existing DOM nodes and event listeners. Use append().
❌ Incorrect
list.innerHTML += "<li>" + item + "</li>"; // Destroys existing child nodes!
✅ Correct
const li = document.createElement("li"); li.textContent = item; list.append(li);Related HTML Tutorials & Compiler
DOM Manipulation: querySelector, textContent, and innerHTML
Select and manipulate HTML elements using document.querySelector and textContent.
DOM Event Listeners: addEventListener, Click, and Input Events
Respond to user actions using addEventListener for click, input, and keyup events.
DOM classList API: add, remove, and toggle CSS Classes
Mutate styles dynamically by toggling CSS classes with element.classList.
HTML Online Compiler
Open in Compilra IDE
Run and test HTML on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.