Creating & Updating Elements
Build new interface elements, insert them in the right place, and update classes, styles, and accessible text safely.
By the end, you’ll be able to…
- Create elements with createElement and insert them with DOM methods.
- Use classList, style, and dataset to express visual state and data.
- Batch list updates with a DocumentFragment.
- Avoid innerHTML injection and keep updates understandable to assistive technology.
01Create nodes instead of strings
createElement builds an element in memory. It is not on the page yet, so you can set its text, classes, and attributes before inserting it. Creating a node and then appending it gives the browser a precise instruction: add this element here. It also keeps user text separated from markup, because you assign that text with textContent rather than concatenating it into an HTML string.
A newly created element has no content. Set textContent for simple text, or append child elements when the content has structure. Attributes such as href, src, and aria-label can be set directly or with setAttribute. Prefer properties when they exist because they are typed and easier to read. Once the node is complete, insert it where it belongs.
02Insert and remove in the right place
append adds a node after the last child; prepend adds it before the first. before and after place a node next to the element you call them on, in that element's parent. remove takes an element out of the document but keeps the object available in memory. replaceChildren swaps every child for a new set, which is useful when a render function rebuilds a small list.
All of these methods accept several nodes or strings. Passing a string creates a text node, which is safe but easy to confuse with markup. A node can only exist in one place: appending an existing element moves it. That behaviour is useful for reordering, but it can surprise you if you expected a copy. Call cloneNode(true) when you truly need a duplicate.
03Classes, styles, and data attributes
classList exposes add, remove, toggle, and contains. Use classes for visual states so styling stays in CSS; toggling a class is clearer than writing several style properties. The style property works for dynamic values, such as a progress width, and uses camelCase names like backgroundColor. For custom properties, call style.setProperty('--progress', '60%').
dataset reads and writes data-* attributes. An attribute named data-item-id appears as dataset.itemId, always a string. Data attributes are a good bridge between markup and event handlers, but they are not a place for secrets or large objects. Keep the DOM as a view of state, not as the only database, and convert numbers explicitly when you read them back.
04Fragments and accessible updates
Adding many nodes one at a time can cause repeated layout work. A DocumentFragment is a lightweight container that holds nodes off-page. Append each new item to the fragment, then append the fragment once; its children move into the document together. The fragment itself disappears from the tree after insertion, which makes it a useful staging area for list renders.
Accessibility is part of updating the page. Change the text of an existing label rather than replacing the label element, so focus and screen-reader context survive. For status messages, use an element with role='status' or aria-live='polite' and update its textContent. Do not rely on colour alone to communicate completion, and keep buttons as real button elements so keyboard users can activate them.
The ideas worth keeping.
- Build elements with createElement and textContent, then insert them with append, prepend, before, or after.
- Use classList for styling states, style for dynamic values, and dataset for small data hooks.
- Stage repeated updates in a DocumentFragment and keep labels, buttons, and status text accessible.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Build a product row
Write a function createProduct(product) that returns an article element containing an h2 with the product name, a paragraph with the formatted price, and a button labelled Add to cart. Store the product id in a data attribute and add the class product. Do not use innerHTML.
Explore a worked solution
function createProduct(product) { const article = document.createElement("article"); article.className = "product"; article.dataset.id = product.id; const heading = document.createElement("h2"); heading.textContent = product.name; const price = document.createElement("p"); price.textContent = "$" + product.price.toFixed(2); const button = document.createElement("button"); button.type = "button"; button.textContent = "Add to cart"; article.append(heading, price, button); return article;}Each value is placed with textContent, so a product name containing angle brackets stays text instead of becoming markup. The returned element can be inserted by the caller.
Exercise 2: Render messages with an empty state
Write renderMessages(messages) that targets #messages, replaces its contents, and shows one p per message inside a fragment. If the array is empty, show a single paragraph saying No messages yet. Throw an error if the container is missing.
Explore a worked solution
function renderMessages(messages) { const container = document.querySelector("#messages"); if (!container) throw new Error("Messages container not found"); const fragment = document.createDocumentFragment(); if (messages.length === 0) { const empty = document.createElement("p"); empty.textContent = "No messages yet"; fragment.append(empty); } else { for (const message of messages) { const item = document.createElement("p"); item.textContent = message; fragment.append(item); } } container.replaceChildren(fragment);}The fragment collects the output before it touches the live document, and replaceChildren clears stale content. The empty branch prevents a blank panel with no explanation.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Build a product row
Write a function createProduct(product) that returns an article element containing an h2 with the product name, a paragraph with the formatted price, and a button labelled Add to cart. Store the product id in a data attribute and add the class product. Do not use innerHTML.
[Process exited with code 0 - No output]
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.