Skip to content
jshacks.dev
Browser

How to Create Elements Dynamically in JavaScript

Create elements dynamically with createElement, append, template and replaceChildren, set text and attributes safely, and add many nodes quickly.

8 min read
Summarize in AI
Flat illustration of a template rendering into a page, with the JavaScript, Google Chrome, Vue.js and HTML5 logos.

Pages that react to data, such as a list of search results, a toast message or a new row in a table, need to create elements while the page is running. The browser gives you several ways to do it, and they differ in safety and speed. Some build real nodes you can attach listeners to; one builds a string that the parser turns into nodes and can open a security hole when it contains user input. This guide shows how to create elements dynamically in JavaScript: document.createElement(), setting text, attributes and classes, inserting with append(), prepend() and before(), building many nodes efficiently with DocumentFragment and replaceChildren(), cloning a <template>, and the cases where innerHTML is acceptable. The methods are part of the DOM Standard and documented on MDN; they work in every current browser.

createElement and append

document.createElement(tagName) returns a new element that is not yet part of the page. Nothing is visible until you insert it into the tree.

create.jsJavaScript
const note = document.createElement("p");
note.textContent = "Saved successfully";
note.className = "note";

document.body.append(note);

console.log(document.body.lastElementChild.outerHTML);
Text
<p class="note">Saved successfully</p>

textContent sets the text of the element and treats the value as plain text, so characters such as < are shown, not parsed. className sets the class attribute as a string. The element exists in memory from the first line and appears when append() attaches it to document.body.

Classes, attributes and data

Use classList to add and remove individual classes, setAttribute() for attributes without a dedicated property, the dataset object for data-* attributes, and the style object or, better, classes for appearance.

attrs.jsJavaScript
const link = document.createElement("a");
link.href = "https://example.com";
link.textContent = "Example";
link.classList.add("external", "link");
link.setAttribute("rel", "noopener");
link.dataset.track = "outbound";
link.target = "_blank";

console.log(link.outerHTML);
Text
<a href="https://example.com" class="external link" rel="noopener" data-track="outbound" target="_blank">Example</a>

Properties such as href, id, type and value are the normal way to set standard attributes. For <input> elements, set type before other properties, because some browsers reset the value when the type changes.

Insert where you need it

append() and prepend() add children at the end or the start of a parent. before() and after() insert siblings, and replaceWith() swaps an element for another. All of them accept several arguments and plain strings, which become text nodes, so you can add text and elements in one call.

insert.jsJavaScript
const list = document.createElement("ul");
document.body.append(list);

const first = document.createElement("li");
first.textContent = "first";
const last = document.createElement("li");
last.textContent = "last";
const middle = document.createElement("li");
middle.textContent = "middle";

list.append(first, last);
last.before(middle);
list.prepend("start: ");

console.log(list.innerHTML);
Text
start: <li>first</li><li>middle</li><li>last</li>

The older appendChild() and insertBefore() still work and return the inserted node, but they take only one node at a time, so the newer methods are shorter. When you insert a node that is already in the document, it is moved, not copied.

Build a helper

A small function that creates an element, applies properties and appends children keeps repeated code short.

helper.jsJavaScript
function el(tag, props = {}, ...children) {
  const node = document.createElement(tag);
  const { dataset, class: className, ...rest } = props;
  if (className) node.className = className;
  if (dataset) Object.assign(node.dataset, dataset);
  Object.assign(node, rest);
  node.append(...children);
  return node;
}

const card = el(
  "article",
  { class: "card", dataset: { id: "7" } },
  el("h2", { textContent: "Title" }),
  el("p", {}, "Body text with a ", el("strong", {}, "bold"), " word"),
);

console.log(card.outerHTML);
Text
<article class="card" data-id="7"><h2>Title</h2><p>Body text with a <strong>bold</strong> word</p></article>

Nothing in the helper parses HTML, so any string passed as a child or as textContent is treated as text. That property is the reason to prefer this style for content that came from a user or an API.

Many elements at once

Adding items one at a time to an element that is already on the page can trigger layout work for every insertion. Build the nodes first, in a DocumentFragment, and attach it once.

fragment.jsJavaScript
const items = ["alpha", "beta", "gamma"];
const fragment = document.createDocumentFragment();

for (const name of items) {
  const li = document.createElement("li");
  li.textContent = name;
  fragment.append(li);
}

const list = document.createElement("ul");
list.append(fragment);
document.body.append(list);

console.log(list.children.length, fragment.children.length);
Text
3 0

When a fragment is appended, its children move into the target and the fragment is left empty, which the second number shows. In current browsers the speed difference for small lists is minor; the fragment matters when you insert hundreds of nodes into a live document, or when you want to prepare the content away from the page before showing it.

Replace the contents of a container

To redraw a list, clear it and add the new items. replaceChildren() does both in one call and does not parse any HTML.

replace.jsJavaScript
const list = document.createElement("ul");
list.innerHTML = "<li>old 1</li><li>old 2</li>";

const nodes = ["new 1", "new 2", "new 3"].map((text) => {
  const li = document.createElement("li");
  li.textContent = text;
  return li;
});

list.replaceChildren(...nodes);
console.log(list.textContent);
Text
new 1new 2new 3

Calling replaceChildren() with no arguments empties the element, which is a faster and safer replacement for innerHTML = "" and does not discard event listeners on the container itself.

Cloning a template

When the markup is more than a few elements, write it once in a <template> and clone it. The content of a template is inert: scripts do not run and images do not load until it is inserted.

template.jsJavaScript
document.body.innerHTML = `
  <template id="row">
    <tr><td class="name"></td><td class="price"></td></tr>
  </template>
  <table><tbody id="rows"></tbody></table>
`;

const template = document.querySelector("#row");
const tbody = document.querySelector("#rows");

for (const [name, price] of [["Pen", "1.50"], ["Book", "12.00"]]) {
  const row = template.content.cloneNode(true);
  row.querySelector(".name").textContent = name;
  row.querySelector(".price").textContent = price;
  tbody.append(row);
}

console.log(tbody.innerHTML);
Text
<tr><td class="name">Pen</td><td class="price">1.50</td></tr><tr><td class="name">Book</td><td class="price">12.00</td></tr>

cloneNode(true) copies the template's content deeply. Fill in the cloned nodes with textContent, then append. Templates are the right tool when designers own the markup, since it stays as HTML.

innerHTML and its risk

element.innerHTML = "<p>...</p>" parses a string and replaces the children. It is short and fast to write, and it is safe when the string is a constant you wrote yourself. It is dangerous when any part comes from outside the program: a name containing <img src=x onerror=...> becomes a real element, and the handler runs. This is cross-site scripting.

unsafe.jsJavaScript
const userInput = '<img src="x" onerror="console.log(1)">';
const safe = document.createElement("div");
safe.textContent = userInput;

console.log(safe.innerHTML);
Text
&lt;img src="x" onerror="console.log(1)"&gt;

Setting textContent escaped the markup, so it is displayed and not executed. If you must insert HTML from elsewhere, sanitize it first, for example with Element.setHTML() where supported, which applies the browser's built-in sanitizer, or a library such as DOMPurify.

Event listeners on new elements

A listener added with addEventListener() stays on the node as it moves. Elements created later will not have listeners added to older ones, so either attach a listener when you create each element, or use delegation: one listener on the container that checks event.target.closest().

listen.jsJavaScript
const list = document.createElement("ul");
document.body.append(list);

list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (item) console.log("clicked", item.textContent);
});

const li = document.createElement("li");
li.textContent = "dynamic";
list.append(li);
li.click();
Text
clicked dynamic

Delegation means the item created after the listener was added still works with no extra code.

Choosing between the approaches

Each technique has a place, and a short rule of thumb saves time. For one or two elements, createElement() with textContent and append() is the clearest choice, and it is safe by construction. For a repeated block of several elements, such as a card with a heading, an image and a button, a <template> keeps the structure in HTML where designers can read it, and cloning it is cheap. For a list that is redrawn from data, build the nodes in a loop and hand them to replaceChildren(), so the old items disappear in the same step as the new ones arrive and the user never sees a half-empty list. For a very large list, creating every node is the wrong approach altogether; render only the rows that are visible, which is what a virtual list does.

Think also about who owns the state. If the same data is displayed in several places, a framework or a small render function that rebuilds the view from the data avoids the bugs that come from updating individual nodes by hand. Creating elements by hand is ideal for widgets that have little state: a toast, a tooltip, a dialog, a row added after a form submit. When you notice yourself writing code to keep a dozen nodes in step with an object, that is the signal that a declarative rendering library would pay for itself.

Accessibility needs a thought too. A node added to the page is not announced to a screen reader unless it lands in a live region. If you create a status message, insert it into an element with role="status" or aria-live="polite" that already exists in the page, since adding an element that carries the attribute at the same moment as its content is often missed. Move focus deliberately when you add content the user must act on, such as a dialog, and return it when the content is removed.

Removing and updating what you created

Creation has a counterpart. element.remove() takes a node out of the document, and replaceWith() swaps it for another. Keep a reference to a created node when you will need it again, because searching for it later costs more than holding it. When nodes are created in a loop and the data changes, decide whether to rebuild everything or patch the existing nodes. Rebuilding is simpler and fast enough for lists of a few hundred items; patching, by keeping a Map from an id to its element, preserves focus, scroll position and input text inside rows, which matters when rows contain form fields.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.