Creating Elements
JavaScript can create new HTML elements on the fly using document.createElement(). The element is created in memory — it won't appear on the page until you add it to the DOM.
const newDiv = document.createElement("div");
newDiv.textContent = "Hello, I'm new here!";
newDiv.className = "greeting";
// Now add it to the page
document.body.appendChild(newDiv);
Inserting Elements
There are several ways to add elements to the DOM. appendChild adds to the end, while insertBefore and prepend give you more control over placement.
const container = document.querySelector("#list");
// Append to the end
container.appendChild(newDiv);
// Insert before a specific child
const reference = container.children[0];
container.insertBefore(newDiv, reference);
// Add as the first child
container.prepend(newDiv);
// Insert HTML as a string (less safe but convenient)
container.insertAdjacentHTML("beforeend", "<li>New item</li>");
Removing Elements
To remove an element, first grab it, then call remove() on it. This is much cleaner than the old parentNode.removeChild() approach.
const item = document.querySelector(".old-item");
item.remove();
Try it Yourself →
Building a List Dynamically
A real-world use case: building a list from an array of data.
const fruits = ["Apple", "Banana", "Cherry"];
const list = document.querySelector("#fruitList");
fruits.forEach(fruit => {
const li = document.createElement("li");
li.textContent = fruit;
list.appendChild(li);
});
Performance Tip
If you're adding many elements at once, avoid appending them one by one. Instead, build a DocumentFragment, add everything to it, then append the fragment in one go. This triggers only one reflow instead of many.
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
document.querySelector("#bigList").appendChild(fragment);