Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 156 ยท The DOM

Creating and Removing Elements

Build page content with createElement, insert it with append, prepend, before and after, move and clone nodes, use templates and remove nodes.

Most interactive pages build part of their content in JavaScript: a list of search results, a new chat message, a row added to a cart, a notification that slides in and disappears. Doing that well means creating elements safely, putting them in exactly the right place and removing them cleanly when they are no longer needed.

You saw the basic recipe in the HTML course's DOM lesson: createElement(), set its text, append() it. This lesson completes the toolkit. You will learn every insertion method, how moving and cloning work, how replaceChildren() makes re-rendering easy, and how <template> elements and document fragments let you build complex markup efficiently.

Creating elements

document.createElement(tagName) returns a brand-new element that is not yet part of the page. It is detached: you can set its text, attributes, classes and listeners freely, and nothing appears on screen until you insert it.

JavaScript
const badge = document.createElement("span");
badge.className = "badge";
badge.textContent = "New";
badge.title = "Added this week";

A text node can be created on its own with document.createTextNode("text"), but you rarely need it: the modern insertion methods accept strings and turn them into text nodes for you.

Because properties like textContent never parse HTML, building elements this way is safe for any data, unlike assigning strings to innerHTML (see Changing Content).

Inserting elements

Modern DOM methods are named after where the new content goes relative to the element you call them on. All of them accept any number of nodes or strings; strings become text.

Method Inserts
parent.append(...items) Inside, after the last child
parent.prepend(...items) Inside, before the first child
el.before(...items) Outside, just before the element
el.after(...items) Outside, just after the element
el.replaceWith(...items) In place of the element
parent.replaceChildren(...items) Replaces all children (none = empty it)
Where things go

The older method appendChild(node) still works everywhere. It accepts exactly one node and no strings, and it returns the appended node. insertBefore(newNode, referenceNode) is its older partner. New code can use append() and friends, which are shorter and more flexible.

There is also insertAdjacentElement(position, element), using the same four position names as insertAdjacentHTML().

A small helper for building elements

Creating an element, setting several properties and adding children takes many lines. A small helper of your own keeps rendering code readable:

JavaScript
function el(tag, props = {}, ...children) {
  const node = document.createElement(tag);
  Object.assign(node, props);   // className, textContent, type, hrefโ€ฆ
  node.append(...children);
  return node;
}

const card = el("article", { className: "card" },
  el("h3", { textContent: "Harbor Cafรฉ" }),
  el("p", { textContent: "Open until 22:00" }),
);

Object.assign() sets properties, so use property names such as className and htmlFor. Attributes without a property, like aria-*, still need setAttribute(), and data-* values can go through dataset.

Moving vs cloning

A node can only be in one place at a time. If you insert a node that is already in the document, it is moved, not copied. Its listeners and state go with it.

That makes reordering cheap: to move an item to the top of a list, just list.prepend(item). To sort a list, sort the elements in an array and append them back in order.

To get a real copy, call node.cloneNode(true). The true means deep: copy all descendants as well. Without it, you only get the element itself, empty. Clones copy attributes, but not listeners added with addEventListener(), so attach those again (or use event delegation).

Moving, sorting and cloning

Click Sort and the three items reorder without any being created or destroyed. Click Clone and you get a genuine fourth item.

Removing elements

element.remove() takes an element out of the document. If you still hold a reference in a variable, the element continues to exist and you can insert it again later; it is only gone for good once nothing refers to it.

To empty an element, element.replaceChildren() with no arguments is the clearest option. You will also see element.textContent = "" and innerHTML = "", which have the same effect. The old way, parent.removeChild(child), still works but needs a reference to the parent.

Re-rendering with replaceChildren()

A common pattern in apps is to keep your data in an array and render it: whenever the data changes, rebuild the list from scratch. replaceChildren() does the swap in a single step:

JavaScript
function render(items) {
  list.replaceChildren(...items.map((item) => el("li", { textContent: item.name })));
}

For lists of a few hundred items, rebuilding like this is fast and keeps your code simple. You will use this pattern in the To-Do App project.

Templates: HTML you clone

Writing large structures with createElement() gets tedious. The <template> element lets you write the markup in HTML instead. Its contents are parsed but inert: not displayed, images not loaded, scripts not run. In JavaScript, template.content is a DocumentFragment holding that markup; clone it, fill in the blanks with textContent, and insert it. (The HTML side is covered in Templates and Web Components.)

Rendering from a template

The third contact's name contains HTML tags, but it appears as literal text, because the values go in through textContent. Templates give you the readability of writing HTML and the safety of building nodes.

Document fragments

A DocumentFragment is a lightweight container that isn't part of the page. You can append many nodes to it, then insert the whole fragment in one go. When you insert a fragment, its children move into the document and the fragment is left empty.

JavaScript
const fragment = document.createDocumentFragment();
for (const name of names) {
  fragment.append(el("li", { textContent: name }));
}
list.append(fragment); // one insertion

Fragments used to be an important performance trick. Today, append(...nodes) and replaceChildren(...nodes) already accept many nodes at once, so you only need an explicit fragment when you build content gradually, in a loop or across several functions. A template's content is also a fragment, which is why the template example worked the same way.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You call list.append(item) where item is already the first child of list. What happens?

    A node can only be in one place. Inserting an existing node moves it, along with its listeners and state.
  2. 2. Which call inserts banner immediately before main as its sibling?

    before() and after() insert outside the element as siblings. prepend() would put the banner inside main.
  3. 3. What does card.cloneNode(true) copy?

    A deep clone copies the subtree and attributes. Listeners registered with addEventListener() are not copied.
  4. 4. Why are a template's contents not shown on the page?

    Template contents are parsed but inert. Clone template.content, fill it in, then insert it.
  5. 5. How do you remove all children of results in one call?

    replaceChildren() with no arguments empties the element. remove() would remove results itself.

Summary

  • createElement() makes detached elements; fill them with properties like textContent before inserting.
  • append(), prepend(), before(), after(), replaceWith() and replaceChildren() accept many nodes and strings at once.
  • Inserting a node that is already in the document moves it; cloneNode(true) makes a deep copy without listeners.
  • remove() takes an element out; replaceChildren() with no arguments empties one.
  • Render lists by rebuilding them from data with replaceChildren().
  • <template> holds inert markup you clone with template.content.cloneNode(true); fragments batch many nodes into one insertion.

Next: Events โ€” listening for clicks, keys and pointer movement, and controlling how listeners behave.