Creating elements

Topic 3 of 5 in Working with the DOM5 min readBeginnerFree course

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.

JavaScript
const note = document.createElement('p');
note.textContent = 'Saved!';
note.className = 'toast';
document.body.append(note);

Three steps: createElement(‘li’) makes an element that exists only in memory; li.textContent = ‘New’ fills it in safely; list.append(li) puts it on the page. Below, list.before(x) inserts outside before the list, list.prepend(x) inside as the first child, list.append(x) inside as the last child, and list.after(x) outside after it. x.remove() takes an element off the page and list.replaceChildren() empties the list.

Step by step

  1. Create — document.createElement('tag') makes a new, empty element. It exists only in memory; nobody can see it yet.
  2. Fill in — set its text, classes, attributes and children. Doing this before inserting is efficient: the browser draws the finished element once.
  3. Insert — attach it somewhere in the DOM, and it appears.
JavaScript
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

JavaScript
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 list

An 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:

JavaScript
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:

JavaScript
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:

JavaScript
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:

HTML
<template id="card">
  <article class="card"><h3></h3><p></p></article>
</template>
JavaScript
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

JavaScript
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:

JavaScript
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:

JavaScript
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.

Exercise

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.

JavaScript
const topics = [
  { title: 'Loops', done: true },
  { title: 'Functions', done: false },
  { title: 'Objects', done: false },
];
const list = document.querySelector('#topics');

Summary

  • document.createElement makes a new element; it isn’t visible until added.
  • append, prepend, before and after put 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 textContent is safer than gluing HTML strings.