Phase 10 — DOM (Very Important)
Module 32 — Creating DOM Elements
Creating elements dynamically is one of the most powerful features of JavaScript. Modern web applications such as Gmail, Facebook, YouTube, Amazon, Trello, and ChatGPT continuously create, update, and remove elements without reloading the page.
JavaScript provides several DOM methods to create and insert new elements into the document.
Overview
| Method | Purpose |
|---|---|
document.createElement() | Create a new HTML element |
document.createTextNode() | Create a text node |
append() | Add element at the end |
appendChild() | Append one child element |
prepend() | Insert at the beginning |
before() | Insert before an element |
after() | Insert after an element |
replaceWith() | Replace an existing element |
remove() | Remove an element |
cloneNode() | Clone an element |
document.createElement()
Creates a new HTML element.
1const heading = document.createElement("h1"); 2 3heading.textContent = "Welcome to JavaScript"; 4 5document.body.append(heading);
Output
1<h1>Welcome to JavaScript</h1>
document.createTextNode()
Creates a text node that can be added to an element.
1const text = document.createTextNode("Learning DOM"); 2 3const paragraph = document.createElement("p"); 4 5paragraph.appendChild(text); 6 7document.body.append(paragraph);
Output
1<p>Learning DOM</p>
append()
Adds one or more nodes to the end of an element.
1const list = document.querySelector("ul"); 2 3const item = document.createElement("li"); 4 5item.textContent = "JavaScript"; 6 7list.append(item);
You can append multiple elements at once.
1list.append(item1, item2, item3);
appendChild()
Adds a single child node to a parent element.
1const div = document.createElement("div"); 2 3const heading = document.createElement("h2"); 4 5heading.textContent = "DOM Tutorial"; 6 7div.appendChild(heading); 8 9document.body.append(div);
appendChild()accepts only one node at a time.
append() vs appendChild()
| append() | appendChild() |
|---|---|
| Multiple nodes | One node only |
| Accepts text | Accepts only Node |
| Modern API | Older API |
prepend()
Adds a node at the beginning of an element.
1const list = document.querySelector("ul"); 2 3const item = document.createElement("li"); 4 5item.textContent = "First Item"; 6 7list.prepend(item);
before()
Inserts an element before another element.
1const heading = document.querySelector("h2"); 2 3const message = document.createElement("p"); 4 5message.textContent = "Welcome"; 6 7heading.before(message);
after()
Inserts an element after another element.
1const heading = document.querySelector("h2"); 2 3const paragraph = document.createElement("p"); 4 5paragraph.textContent = "Learning JavaScript"; 6 7heading.after(paragraph);
replaceWith()
Replaces an existing element.
1const oldHeading = document.querySelector("h2"); 2 3const newHeading = document.createElement("h1"); 4 5newHeading.textContent = "Modern JavaScript"; 6 7oldHeading.replaceWith(newHeading);
remove()
Removes an element from the DOM.
1const button = document.querySelector("button"); 2 3button.remove();
cloneNode()
Creates a copy of an existing element.
Shallow Clone
1const card = document.querySelector(".card"); 2 3const copy = card.cloneNode(); 4 5document.body.append(copy);
Copies only the element.
Deep Clone
1const card = document.querySelector(".card"); 2 3const copy = card.cloneNode(true); 4 5document.body.append(copy);
Copies the element and all of its children.
Practical Example
HTML
1<div id="container"></div>
JavaScript
1const container = document.getElementById("container"); 2 3const card = document.createElement("div"); 4 5card.className = "card"; 6 7const title = document.createElement("h2"); 8 9title.textContent = "JavaScript DOM"; 10 11const description = document.createElement("p"); 12 13description.textContent = "Creating Elements Dynamically"; 14 15card.append(title, description); 16 17container.append(card);
Mini Project — Dynamic Todo List
HTML
1<input type="text" id="task"> 2 3<button id="addBtn"> 4 Add Task 5</button> 6 7<ul id="list"></ul>
JavaScript
1const input = document.getElementById("task"); 2 3const button = document.getElementById("addBtn"); 4 5const list = document.getElementById("list"); 6 7button.addEventListener("click", () => { 8 9 if (input.value.trim() === "") return; 10 11 const item = document.createElement("li"); 12 13 item.textContent = input.value; 14 15 list.appendChild(item); 16 17 input.value = ""; 18 19});
This project demonstrates:
createElement()appendChild()textContent- Event handling
Common Mistakes
Forgetting to Append the Element
❌ Wrong
1const div = document.createElement("div");
The element exists in memory but is not displayed until it is inserted into the DOM.
✅ Correct
1document.body.append(div);
Using cloneNode() Without true
1const copy = element.cloneNode();
Only the element is copied.
To copy child elements:
1const copy = element.cloneNode(true);
Using appendChild() for Multiple Elements
❌ Wrong
1parent.appendChild(div, p);
✅ Correct
1parent.append(div, p);
Best Practices
- Use
createElement()instead of constructing HTML strings whenever possible. - Prefer
append()for inserting multiple nodes or text. - Use
appendChild()when working with a single DOM node. - Use
cloneNode(true)to duplicate elements with all child content. - Remove unused elements with
remove()to keep the DOM clean. - Build complex elements in memory first, then append them to the DOM to minimize reflows and improve performance.
Interview Questions
Q1. What is the difference between append() and appendChild()?
append()can insert multiple nodes and text.appendChild()inserts only one node and returns the appended node.
Q2. What is the difference between cloneNode() and cloneNode(true)?
cloneNode()creates a shallow copy of the element.cloneNode(true)creates a deep copy, including all descendant elements.
Q3. When should you use createTextNode()?
Use it when you want to create a text node explicitly and append it to an element, especially when building DOM structures programmatically.
Q4. How do you replace an existing DOM element?
Use the replaceWith() method on the element you want to replace and pass the new node as its argument.
Summary
In this module, you learned how to dynamically create, insert, replace, clone, and remove DOM elements using JavaScript. You explored methods such as createElement(), createTextNode(), append(), appendChild(), prepend(), before(), after(), replaceWith(), remove(), and cloneNode(). These APIs form the foundation for building interactive user interfaces without reloading the page.
Next Module: Module 33 — DOM Content & Attributes, where you'll learn
textContent,innerHTML,innerText,setAttribute(),getAttribute(),removeAttribute(),dataset,classList, andstylefor dynamically updating HTML content and element properties.