HTML:Dynamic DOM: document.createElement and appendChild
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:

ParameterTypeDescription
document.createElement()MethodCreates specified HTML element node.
append()MethodAppends element node or string to container.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test HTML on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

HTML Online Compiler