Creating elements
Overview
You can create elements from scratch, fill them in, and place them anywhere on the page. This is how apps show data that isn’t in the HTML file: search results, new chat messages, items added to a cart.
const note = document.createElement('p');
note.textContent = 'Saved!';
note.className = 'toast';
document.body.append(note);Step by step
- Create —
document.createElement('tag')makes a new, empty element. It exists only in memory; nobody can see it yet. - Fill in — set its text, classes, attributes and children. Doing this before inserting is efficient: the browser draws the finished element once.
- Insert — attach it somewhere in the DOM, and it appears.
const link = document.createElement('a');
link.href = '/courses/javascript-essentials/';
link.textContent = 'JavaScript Essentials';
link.classList.add('course-link');
link.dataset.course = 'js';
document.querySelector('nav').append(link);Placing elements
const list = document.querySelector('ul');
const item = document.createElement('li');
item.textContent = 'New topic';
list.append(item); // last child
list.prepend(item); // first child
list.before(item); // just before the list
list.after(item); // just after the listAn element can only be in one place at a time. Appending an element that’s already on the page moves it — handy for reordering.
These methods accept several items, and plain strings become text:
paragraph.append('Read the ', link, ' for details.');To place something relative to another element’s position, use insertAdjacentElement, or select the neighbour and use before/after.
Building several at once
Adding elements one by one makes the browser redraw repeatedly. Build them in a DocumentFragment first, then add it once:
const fragment = document.createDocumentFragment();
for (const title of titles) {
const li = document.createElement('li');
li.textContent = title;
fragment.append(li);
}
list.append(fragment);A fragment is an invisible container: when you append it, its children move into the page and the fragment itself disappears.
A small helper
Creating elements can get repetitive. A tiny helper function makes it tidier:
function el(tag, props = {}, ...children) {
const node = document.createElement(tag);
Object.assign(node, props);
node.append(...children);
return node;
}
const card = el('article', { className: 'card' },
el('h3', { textContent: 'Closures' }),
el('p', { textContent: 'Functions that remember.' }),
);
document.querySelector('.cards').append(card);Templates
For bigger chunks, write the HTML once in a <template> and clone it:
<template id="card">
<article class="card"><h3></h3><p></p></article>
</template>const tpl = document.querySelector('#card');
const card = tpl.content.cloneNode(true);
card.querySelector('h3').textContent = 'Closures';
document.querySelector('.cards').append(card);The contents of a <template> aren’t shown and don’t run. cloneNode(true) makes a deep copy you can fill in and insert as many times as you like. This keeps your HTML structure in HTML, where it’s easy to read, and your data handling in JavaScript.
Removing
note.remove();
list.replaceChildren(); // removes all children
list.replaceChildren(newItem1, newItem2); // or replace them all at once
oldItem.replaceWith(newItem);A common pattern for re-drawing a list from data is to clear it and rebuild it:
function render(topics) {
list.replaceChildren(
...topics.map((t) => {
const li = document.createElement('li');
li.textContent = t.title;
return li;
}),
);
}Call render whenever the data changes. (Frameworks like React do this for you, more cleverly — but the idea is the same.)
Why not just use innerHTML?
You can build HTML as a string:
list.innerHTML = topics.map((t) => `<li>${t.title}</li>`).join('');It’s quick to write, and fine for content you fully control. But if t.title comes from a user or a server, it could contain HTML or a script — the XSS problem from the previous topic. Creating elements and setting textContent is always safe. Setting innerHTML also throws away any existing elements inside, along with their event listeners.
Render a list
Given an array of topic objects, add one <li> per topic to the <ul id="topics">. Give finished topics the class done, and add a small “Remove” button to each item that deletes it.
const topics = [
{ title: 'Loops', done: true },
{ title: 'Functions', done: false },
{ title: 'Objects', done: false },
];
const list = document.querySelector('#topics');const list = document.querySelector('#topics');
for (const topic of topics) {
const li = document.createElement('li');
li.textContent = topic.title;
li.classList.toggle('done', topic.done);
const remove = document.createElement('button');
remove.textContent = 'Remove';
remove.addEventListener('click', () => li.remove());
li.append(' ', remove);
list.append(li);
}Summary
document.createElementmakes a new element; it isn’t visible until added.append,prepend,beforeandafterput elements (or text) on the page.element.remove()takes an element off the page;replaceChildren()empties one.- Build many elements in a fragment, or clone a
<template>, then insert once. - Building elements with
textContentis safer than gluing HTML strings.