Creating and removing elements dynamically
Build page content with code: createElement, append, remove, clone, and render lists from data.
In this lesson you will
- Create, fill and place elements
- Remove, clone and empty containers
- Render lists from arrays of data
- Choose safe and fast approaches
About 18 minutes
Building the page with code
So far you have changed things that were already in the HTML. But what about a to-do list where the visitor adds ten items, or a news feed with fifty posts that arrive from a server? You cannot write that HTML in advance. JavaScript can create new elements from nothing, put them into the page, and remove them again. That is how almost every dynamic site works.
createElement and append
const list = document.querySelector("#list");
const item = document.createElement("li"); // new, not yet on the page
item.textContent = "Learn the DOM";
item.classList.add("task");
list.append(item); // now it appears at the end
Three steps, always in this order: create the element, fill it with text, attributes and classes, then place it into the page. Until you place it, nobody can see it.
Create three list items in a loop from the array and add them to the list.
<ul id="list"></ul>
<script>
const skills = ['HTML', 'CSS', 'JavaScript'];
const list = document.getElementById('list');
// loop and append an li for each skill
</script>
for (const s of skills) { const li = document.createElement(‘li’); li.textContent = s; list.append(li); }
<ul id="list"></ul>
<script>
const skills = ['HTML', 'CSS', 'JavaScript'];
const list = document.getElementById('list');
for (const s of skills) {
const li = document.createElement('li');
li.textContent = s;
list.append(li);
}
</script>
Where to put new elements
| Method | Places the new node |
|---|---|
parent.append(el) |
At the end inside parent |
parent.prepend(el) |
At the start inside parent |
el.before(newEl) |
Just before el |
el.after(newEl) |
Just after el |
el.replaceWith(newEl) |
Instead of el |
parent.insertAdjacentHTML(pos, html) |
Insert an HTML string at a position |
Removing and cloning
const old = document.querySelector(".ad");
old.remove(); // gone
const card = document.querySelector(".card");
const copy = card.cloneNode(true); // true = copy children too
document.body.append(copy);
list.innerHTML = ""; // empty a container quickly
A template string for bigger chunks
const posts = [
{ title: "Learn CSS", views: 120 },
{ title: "Learn JS", views: 340 }
];
list.innerHTML = posts
.map(p => `<li><strong>${p.title}</strong> (${p.views} views)</li>`)
.join("");
This pattern, array.map(...).join("") with a template literal, is the shortest way to render a list. Be careful: it is safe only when you control the data. If any text came from users, build elements with createElement and textContent instead.
Build a card for each product using map and a template literal, and show them inside #shop.
<style>
body{font-family:Arial;padding:12px}
.card{border:1px solid #E6E1F5;border-radius:12px;padding:12px;margin-bottom:8px}
.card b{color:#5A28C8}
</style>
<div id="shop"></div>
<script>
const products = [
{ name: 'Notebook', price: 120 },
{ name: 'Pen', price: 45 },
{ name: 'Bag', price: 900 }
];
// render a .card for each product
</script>
shop.innerHTML = products.map(p => `
Rs ${p.price}
`).join(”);
<style>
body{font-family:Arial;padding:12px}
.card{border:1px solid #E6E1F5;border-radius:12px;padding:12px;margin-bottom:8px}
.card b{color:#5A28C8}
</style>
<div id="shop"></div>
<script>
const products = [
{ name: 'Notebook', price: 120 },
{ name: 'Pen', price: 45 },
{ name: 'Bag', price: 900 }
];
const shop = document.getElementById('shop');
shop.innerHTML = products
.map(p => `<div class="card"><b>${p.name}</b><br>Rs ${p.price}</div>`)
.join('');
</script>
Adding elements from a form
Make the Add button append the typed text as a new list item, then clear the box. Do nothing if the box is empty.
<style>body{font-family:Arial;padding:12px} input{padding:8px;font-size:15px} button{padding:8px 14px;background:#5A28C8;color:#fff;border:0;border-radius:8px} li{margin:6px 0}</style>
<input id="t" placeholder="New task">
<button id="add">Add</button>
<ul id="list"></ul>
<script>
const t = document.getElementById('t');
const list = document.getElementById('list');
document.getElementById('add').addEventListener('click', function () {
// read t.value, create li, append, clear
});
</script>
const text = t.value.trim(); if (!text) return; then create the li, append it, set t.value = ” and t.focus().
<style>body{font-family:Arial;padding:12px} input{padding:8px;font-size:15px} button{padding:8px 14px;background:#5A28C8;color:#fff;border:0;border-radius:8px} li{margin:6px 0}</style>
<input id="t" placeholder="New task">
<button id="add">Add</button>
<ul id="list"></ul>
<script>
const t = document.getElementById('t');
const list = document.getElementById('list');
document.getElementById('add').addEventListener('click', function () {
const text = t.value.trim();
if (!text) return;
const li = document.createElement('li');
li.textContent = text;
list.append(li);
t.value = '';
t.focus();
});
</script>
DocumentFragment for many items
const frag = document.createDocumentFragment();
for (let i = 1; i <= 100; i++) {
const li = document.createElement("li");
li.textContent = "Item " + i;
frag.append(li);
}
list.append(frag); // one single update
A fragment is an invisible holder. Appending hundreds of items to it and then inserting it once is faster than touching the live page a hundred times.
Choosing a method
- Few elements, user text:
createElementandtextContent. - Many elements from trusted data:
map, template literals,innerHTML. - Huge lists: a
DocumentFragment, or showing only part of the list at a time.
Using innerHTML += in a loop. It re-parses and rebuilds the whole container every time, and destroys event listeners attached to existing children. Build a string first and assign once, or use append.
If each new item needs a delete button, attach the listener when you create it, or better, use event delegation, which the next lesson explains.
Worked example: a gallery from a list
A gallery is an array of picture addresses turned into elements. You write the data once, and the code builds as many figures as you like. Adding a picture later means adding one line to the array and nothing else.
const photos = [
{ src: "sea.jpg", caption: "The sea" },
{ src: "hill.jpg", caption: "The hills" },
{ src: "city.jpg", caption: "The city" }
];
const gallery = document.querySelector("#gallery");
for (const p of photos) {
const fig = document.createElement("figure");
const img = document.createElement("img");
img.src = p.src;
img.alt = p.caption;
const cap = document.createElement("figcaption");
cap.textContent = p.caption;
fig.append(img, cap);
gallery.append(fig);
}
Look at how the structure of the code mirrors the structure of the HTML you would otherwise write by hand: a figure containing an image and a caption.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is the correct order to add a new element?
- Place, create, fill
- Fill, place, create
- Create, fill, place
- Place only
Create it, fill it, then put it in the page.
Which removes an element from the page?
el.remove()el.delete()el.hide()el.clear()
remove() takes it out of the DOM.
What does cloneNode(true) do?
- Deletes it
- Copies the element and its children
- Moves it
- Copies only the tag
true means a deep copy.
Why avoid innerHTML += in a loop?
- It is invalid
- It only works once
- It is encrypted
- It rebuilds the container each time and drops listeners
It is slow and removes listeners.
Which is safest for text a visitor typed?
innerHTMLcreateElementwithtextContentevaldocument.write
textContent never runs markup.
Summary
- Create, fill, then place an element.
- remove() and cloneNode() manage existing nodes.
- map plus join renders lists quickly from trusted data.
- Use textContent for user text.
Questions
Is innerHTML bad?
Not bad, but unsafe with user-supplied text and slow in loops. Use it for trusted templates.
How do I insert at a specific position?
Use before, after, prepend, or insertAdjacentHTML with beforebegin, afterbegin, beforeend or afterend.
Why does my new element have no style?
Check it has the right class and that it was placed inside a container your CSS covers.
