JavaScript allows you to create new HTML elements, add them to a webpage, remove existing elements, and replace elements dynamically. These operations are part of DOM manipulation and help you build interactive webpages without reloading the entire page.
The DOM provides several methods for working with HTML elements, including createElement(), append(), appendChild(), prepend(), remove(), and replaceWith().
In this tutorial, you will learn how each method works, how to use it with practical examples, and the differences between similar methods.
Creating HTML Elements with createElement()
The createElement() method creates a new HTML element in memory. The element does not automatically appear on the webpage. You must insert it into the DOM using a method such as append() or appendChild().
Syntax of createElement()
document.createElement("tagName");
The tagName argument specifies the HTML element you want to create, such as "p", "div", "h2", or "button".
Example of createElement()
const paragraph = document.createElement("p");
paragraph.textContent = "Hello, JavaScript!";
console.log(paragraph.textContent);
Output:
Hello, JavaScript!
This code creates a paragraph element and sets its text. However, the paragraph is not visible on the webpage because it has not yet been inserted into the document.
Creating and Displaying an Element
HTML:
<div id="container"></div>
JavaScript:
const container = document.querySelector("#container");
const paragraph = document.createElement("p");
paragraph.textContent = "This paragraph was created using JavaScript.";
container.append(paragraph);
The paragraph is now added inside the container element and appears on the webpage.
Setting Attributes on a New Element
You can set attributes, classes, and styles before inserting a newly created element.
const link = document.createElement("a");
link.textContent = "Visit Web4Learners";
link.setAttribute("href", "https://web4learners.com");
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener");
document.body.append(link);
This example creates a link, sets its attributes, and appends it to the document body.
Adding Elements with append()
The append() method inserts one or more nodes or text strings at the end of an element’s existing content.
It is useful when you want to add new content without replacing the content already inside a parent element.
Syntax of append()
parentElement.append(node);
You can also append multiple items in one call:
parentElement.append(node1, node2, "Some text");
Example of append()
HTML:
<ul id="languages">
<li>HTML</li>
<li>CSS</li>
</ul>
JavaScript:
const languages = document.querySelector("#languages");
const item = document.createElement("li");
item.textContent = "JavaScript";
languages.append(item);
Updated HTML:
<ul id="languages">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
The new list item is added at the end of the list.
Appending Multiple Elements
The append() method can insert several elements in a single call.
const container = document.querySelector("#container");
const heading = document.createElement("h2");
heading.textContent = "JavaScript Tutorial";
const paragraph = document.createElement("p");
paragraph.textContent = "Learn DOM manipulation.";
container.append(heading, paragraph);
Both elements are inserted at the end of the container, in the order supplied.
Appending Text
Unlike appendChild(), the append() method also accepts strings.
const container = document.querySelector("#container");
container.append("Welcome to JavaScript!");
The text is added as a text node inside the container.
Important: A string passed to append() is treated as text, not parsed as HTML. For example, container.append("<strong>Hello</strong>") displays the angle brackets as text rather than creating a strong element.
Adding Elements with appendChild()
The appendChild() method inserts a node at the end of a parent element’s child nodes.
It is commonly used to add elements created with createElement().
Syntax of appendChild()
parentElement.appendChild(node);
The node argument must be a DOM node, such as an element created using createElement() or an existing node in the document.
Example of appendChild()
HTML:
<div id="container"></div>
JavaScript:
const container = document.querySelector("#container");
const paragraph = document.createElement("p");
paragraph.textContent = "Added using appendChild().";
container.appendChild(paragraph);
The paragraph is inserted at the end of the container and becomes visible on the webpage.
Returning the Appended Node
The appendChild() method returns the node that was inserted.
const container = document.querySelector("#container");
const heading = document.createElement("h2");
heading.textContent = "Welcome";
const addedHeading = container.appendChild(heading);
console.log(addedHeading === heading);
Output:
true
The returned value is the same node that was appended.
Moving an Existing Element
If you append a node that already exists in the document, JavaScript moves it to the new location rather than creating a duplicate.
<div id="first">
<p id="message">Hello</p>
</div>
<div id="second"></div>
const message = document.querySelector("#message");
const second = document.querySelector("#second");
second.appendChild(message);
The paragraph is moved from first into second.
Difference Between append() and appendChild()
Both methods add content to the end of a parent element, but they support different types of arguments.
| Feature | append() | appendChild() |
|---|---|---|
| Accepts DOM nodes | Yes | Yes |
| Accepts text strings directly | Yes | No |
| Accepts multiple arguments | Yes | No, one node at a time |
| Return value | undefined | The appended node |
| Common use | Adding nodes and text together | Appending a single DOM node |
For example:
const container = document.querySelector("#container");
container.append("Hello ", "JavaScript!");
This is valid because append() accepts multiple strings.
However, appendChild() requires a node:
const paragraph = document.createElement("p");
paragraph.textContent = "Hello, JavaScript!";
container.appendChild(paragraph);
Use append() when you need to add multiple nodes or text strings. Use appendChild() when you want to append a single node and possibly use the returned node.
Adding Elements at the Beginning with prepend()
The prepend() method inserts one or more nodes or text strings at the beginning of an element’s child nodes.
It is useful when you want new content to appear before existing content.
Syntax of prepend()
parentElement.prepend(node);
Like append(), it can accept multiple items:
parentElement.prepend(node1, node2, "Some text");
Example of prepend()
HTML:
<ul id="languages">
<li>CSS</li>
<li>JavaScript</li>
</ul>
JavaScript:
const languages = document.querySelector("#languages");
const item = document.createElement("li");
item.textContent = "HTML";
languages.prepend(item);
Updated HTML:
<ul id="languages">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
The new item appears before the existing list items.
Prepending a Heading
const container = document.querySelector("#container");
const heading = document.createElement("h2");
heading.textContent = "Important Notice";
container.prepend(heading);
The heading is inserted before the container’s existing child nodes.
Difference Between append() and prepend()
| Feature | append() | prepend() |
|---|---|---|
| Insertion position | End of child nodes | Beginning of child nodes |
| Accepts multiple arguments | Yes | Yes |
| Accepts strings | Yes | Yes |
| Return value | undefined | undefined |
Use append() to add content at the end and prepend() to add content at the beginning.
Removing Elements with remove()
The remove() method removes an element or another node from the DOM.
It is useful when you want to delete an element from a webpage in response to a user action or another event.
Syntax of remove()
element.remove();
You call remove() directly on the element you want to remove.
Example of remove()
HTML:
<p id="message">This paragraph will be removed.</p>
JavaScript:
const message = document.querySelector("#message");
message.remove();
The paragraph is removed from the document and is no longer displayed.
Removing an Element on Button Click
HTML:
<p id="message">Click the button to remove this message.</p>
<button id="removeButton">Remove Message</button>
JavaScript:
const message = document.querySelector("#message");
const button = document.querySelector("#removeButton");
button.addEventListener("click", function () {
message.remove();
});
When the user clicks the button, the paragraph is removed from the webpage.
Removing a List Item
<ul id="tasks">
<li id="task1">Learn HTML</li>
<li id="task2">Learn CSS</li>
<li id="task3">Learn JavaScript</li>
</ul>
const task = document.querySelector("#task2");
task.remove();
The second list item, Learn CSS, is removed, while the other items remain.
Replacing Elements with replaceWith()
The replaceWith() method replaces an existing node with one or more new nodes or text strings.
It is useful when you want to update the structure of a webpage by replacing an element entirely.
Syntax of replaceWith()
existingElement.replaceWith(newNode);
You can also supply multiple nodes or strings:
existingElement.replaceWith(node1, node2, "Some text");
Example of replaceWith()
HTML:
<p id="message">Original message</p>
JavaScript:
const message = document.querySelector("#message");
const heading = document.createElement("h2");
heading.textContent = "Updated Heading";
message.replaceWith(heading);
Updated HTML:
<h2>Updated Heading</h2>
The paragraph is replaced by the new heading.
Replacing an Element with Text
You can replace an element with a text string.
<div id="container">
<p id="message">Old content</p>
</div>
const message = document.querySelector("#message");
message.replaceWith("New text content");
Updated HTML:
<div id="container">
New text content
</div>
The paragraph element is removed and its replacement is a text node.
Replacing One Element with Another
<button id="oldButton">Old Button</button>
const oldButton = document.querySelector("#oldButton");
const newButton = document.createElement("button");
newButton.textContent = "New Button";
newButton.id = "newButton";
oldButton.replaceWith(newButton);
The old button is replaced with a newly created button.
Important: The new button does not automatically inherit event listeners or other JavaScript state attached directly to the old button. If the replacement needs those behaviors, attach the necessary listeners to the new element or use an appropriate event-delegation pattern.
Difference Between remove() and replaceWith()
Both methods can remove an existing element from its original position, but they serve different purposes.
| Feature | remove() | replaceWith() |
|---|---|---|
| Main purpose | Remove an element | Replace an element with other content |
| Inserts replacement content | No | Yes |
| Accepts replacement nodes or strings | No | Yes |
| Typical use | Deleting a message or list item | Replacing a paragraph with a heading |
For example, message.remove() deletes the message. In contrast, message.replaceWith(newHeading) removes the message and inserts a heading in its place.
Complete Example of DOM Element Creation
The following example combines createElement(), append(), prepend(), and remove() to build a simple task list.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Element Creation</title>
</head>
<body>
<h2>My Tasks</h2>
<input id="taskInput" type="text" placeholder="Enter a task">
<button id="addButton">Add Task</button>
<button id="addFirstButton">Add at Beginning</button>
<ul id="taskList"></ul>
<script>
const input = document.querySelector("#taskInput");
const addButton = document.querySelector("#addButton");
const addFirstButton = document.querySelector("#addFirstButton");
const taskList = document.querySelector("#taskList");
function createTask() {
const text = input.value.trim();
if (!text) {
return;
}
const item = document.createElement("li");
const removeButton = document.createElement("button");
item.append(document.createTextNode(text), " ");
removeButton.textContent = "Remove";
removeButton.addEventListener("click", function () {
item.remove();
});
item.append(removeButton);
return item;
}
addButton.addEventListener("click", function () {
const item = createTask();
if (item) {
taskList.append(item);
input.value = "";
}
});
addFirstButton.addEventListener("click", function () {
const item = createTask();
if (item) {
taskList.prepend(item);
input.value = "";
}
});
</script>
</body>
</html>
In this example:
createElement()creates each task and its remove button.append()adds text and the remove button inside each task.append()adds new tasks at the end of the list.prepend()inserts a task at the beginning of the list.remove()deletes a task when its remove button is clicked.
The example uses textContent for the button label and a text node for the task description, so user-entered task text is not interpreted as HTML.
Common Mistakes When Creating Elements
Forgetting to Insert a Created Element
Creating an element does not automatically display it.
const paragraph = document.createElement("p");
paragraph.textContent = "Hello!";
The paragraph exists in memory, but it is not part of the document until you insert it.
Correct:
document.body.append(paragraph);
Passing a String to appendChild()
This does not work:
container.appendChild("Hello");
appendChild() expects a DOM node, not a string.
Use append():
container.append("Hello");
Or create a text node:
const text = document.createTextNode("Hello");
container.appendChild(text);
Trying to Remove a Missing Element
If a selector returns null, calling remove() on the result will throw an error.
const message = document.querySelector("#missingMessage");
if (message) {
message.remove();
}
Checking that the element exists before operating on it prevents this problem.
Frequently Asked Questions
What does createElement() do in JavaScript?
The createElement() method creates a new HTML element object. You must insert it into the DOM before it appears on the webpage.
What is the difference between append() and appendChild()?
append() accepts multiple nodes and strings, while appendChild() accepts a single DOM node and returns the appended node.
What is the difference between append() and prepend()?
append() inserts content at the end of an element’s child nodes, while prepend() inserts content at the beginning.
How do I remove an HTML element using JavaScript?
Select the element and call its remove() method, such as document.querySelector("#message").remove(). Check that the element exists before calling the method when the selector might not match anything.
What does replaceWith() do?
The replaceWith() method replaces an element with one or more nodes or text strings.
Can I move an existing element using appendChild()?
Yes. Appending an existing node to another parent moves it from its original position rather than creating a duplicate.
Do dynamically created elements support event listeners?
Yes. You can attach event listeners to newly created elements using methods such as addEventListener(). If you replace an element, listeners attached directly to the old element are not automatically transferred to the replacement.
Conclusion
JavaScript provides several methods for creating and modifying HTML elements dynamically.
Use createElement() to create new elements, append() and appendChild() to add content at the end, and prepend() to insert content at the beginning. Use remove() to delete elements and replaceWith() to replace existing elements with new content.
Understanding these methods helps you build dynamic lists, interactive forms, notifications, and other webpage components using JavaScript DOM manipulation.
1 thought on “JavaScript Creating and Removing HTML Elements”
Comments are closed.