JavaScript: Creating and Removing HTML Elements
In JavaScript, you can dynamically create, add, and remove elements from the DOM using simple methods. This is essential for building interactive web applications like to-do lists, modals, dynamic forms, and more.
1. Creating an HTML Element
Use document.createElement() to create a new element in JavaScript.
Example:
<div id="container"></div>
<script>
const newElement = document.createElement("p"); // create
newElement.textContent = "Hello from JavaScript!"; // add text
document.getElementById("container").appendChild(newElement); //
add to DOM
</script>
Output
A <p> element with the text appears inside the #container.
2. Creating Elements with Attributes
You can add classes, IDs, styles, or event listeners to elements.
Example:
const button = document.createElement("button");
button.textContent = "Click Me";
button.className = "btn";
button.style.backgroundColor = "green";
button.addEventListener("click", () => {
alert("Button created dynamically!");
});
document.body.appendChild(button);
3. Adding HTML with innerHTML (Not Recommended for User Input)
document.getElementById("container").innerHTML += "<p>Quick
insert</p>";
Note: innerHTML can be less secure and slower — use it carefully, especially with user-generated content.
4. Removing Elements
Use .remove() or .removeChild() to delete elements from the DOM.
Example with .remove():
<p id="removeMe">This will be removed</p>
<button onclick="removeText()">Remove</button>
<script>
function removeText() {
document.getElementById("removeMe").remove();
}
</script>
Example with .removeChild():
<ul id="list">
<li>Item 1</li>
</ul>
<button onclick="removeItem()">Remove List Item</button>
<script>
function removeItem() {
const list = document.getElementById("list");
const item = list.querySelector("li");
if (item) list.removeChild(item);
}
</script>
5. Replace an Element
<ul id="list">
<li>Item 1</li>
</ul>
<button onclick="removeItem()">Remove List Item</button>
<script>
function removeItem() {
const list = document.getElementById("list");
const item = list.querySelector("li");
if (item) list.removeChild(item);
}
</script>
Use .replaceChild() to swap elements.
const newDiv = document.createElement("div");
newDiv.textContent = "I replaced something!";
const oldElement = document.getElementById("old");
document.body.replaceChild(newDiv, oldElement);
Real-World Use Cases
- To-do list items
- Comment boxes
- Shopping carts
- Alerts/modals/popups