SmartCodingTips

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.