Creating and Removing Elements in JavaScript
JavaScript gives you full control over the document structure. You can dynamically create, insert, remove, or replace HTML elements using DOM methods.
π οΈ Creating Elements
// Create a new element
const newDiv = document.createElement("div");
newDiv.textContent = "Hello, I'm new!";
newDiv.classList.add("bg-yellow-100", "p-2", "rounded");
// Append to an existing element
document.body.appendChild(newDiv);
π Insert Before Specific Element
const parent = document.getElementById("container");
const reference = document.getElementById("child-2");
parent.insertBefore(newDiv, reference);
π§½ Removing Elements
const element = document.getElementById("toRemove");
element.remove(); // Removes the element from the DOM
π Replacing Elements
const newElement = document.createElement("p");
newElement.textContent = "Replacement content";
const oldElement = document.getElementById("old");
oldElement.parentNode.replaceChild(newElement, oldElement);
π§ͺ Practical Example
<div id="list"></div>
<button onclick="addItem()">Add Item</button>
<script>
function addItem() {
const li = document.createElement("li");
li.textContent = "New item";
document.getElementById("list").appendChild(li);
}
</script>
β
Tip: Always use
createElement
for dynamic UIs like modals, lists, or messages. Donβt use innerHTML
to add elements β it can break performance and security.