Changing the DOM: Attributes, dataset, textContent, innerHTML and Creating Elements
Modify web pages with JavaScript: attributes vs properties, value vs defaultValue, classList and dataset, textContent vs innerHTML and the XSS risk, insertAdjacentHTML, createElement, append, before, after, replaceWith and remove, cloning, DocumentFragment, templates and a table of contents.
kvi5hnuCode Sprout team member7 min readOn this page
Article 109 found elements; this article changes them. There are three kinds of change: setting an element's attributes, replacing its content, and creating, moving and removing nodes. Getting these right is also where most front-end security bugs are prevented or created.
Attributes as properties
HTML attributes are mirrored by properties on the element objects, and the properties are usually the easiest way to use them:
const logo = document.querySelector("#logo");
logo.src; // the full, resolved URL, e.g. "https://shop.example/img/logo.png"
logo.alt = "Fresh Tea logo";
const form = document.querySelector("form");
form.action = "/api/subscribe";
form.method = "post";
The naming rules:
- Property names are camelCase:
tabindexbecomestabIndexandmaxlengthbecomesmaxLength. (Event handler properties likeonclickstay lowercase.) - Attribute names that are reserved words get new names:
classbecomesclassName, andfor(on<label>) becomeshtmlFor. - Properties have real types:
input.maxLengthis a number,checkbox.checkedandinput.requiredare booleans, anda.hrefis a fully resolved URL even if the attribute was relative.
The generic attribute methods
getAttribute, setAttribute, hasAttribute, removeAttribute and toggleAttribute work with the raw attribute strings. You need them for non-standard attributes, to see the exact value as written, and to remove an attribute (setting a property to null or using delete doesn't do that):
const email = document.querySelector("#email"); // <input id="email" value="a@b.c" required>
email.setAttribute("placeholder", "you@example.com");
email.placeholder; // "you@example.com"
email.hasAttribute("required"); // true
email.removeAttribute("required");
email.required; // false
email.toggleAttribute("required"); // adds it back; returns true
value vs defaultValue
For form fields, the attribute and the property can disagree. The value attribute is the initial value, reflected by defaultValue. The value property is what the user has typed now:
email.value = "new@site.org"; // what the field shows
email.value; // "new@site.org"
email.defaultValue; // "a@b.c" (unchanged)
email.getAttribute("value"); // "a@b.c" (unchanged)
The same split exists for checkboxes (checked vs defaultChecked). Resetting a form restores the default values, and serializing the page (outerHTML) shows the attributes, not what the user typed.
classList
className is the whole class attribute as a single string. To work with individual classes, use classList, a set-like object:
const spinner = document.querySelector("#spinner");
spinner.classList.add("visible", "spinning");
spinner.classList.remove("hidden");
spinner.classList.toggle("dark", prefersDark); // second argument forces add (true) or remove (false)
spinner.classList.contains("visible"); // true
spinner.classList.replace("spinning", "paused");
Toggling classes, with the styles defined in CSS, is the cleanest way to change how things look (article 111).
dataset: data-* attributes
Any attribute starting with data- is valid HTML and free for your own use: IDs, state flags, configuration. element.dataset exposes them with the prefix removed and dashed names converted to camelCase:
// <h2 data-section-number="1.2" data-collapsed>Install</h2>
const heading = document.querySelector("h2");
heading.dataset.sectionNumber; // "1.2"
heading.dataset.collapsed; // "" (present but empty)
heading.dataset.ownerId = "42"; // adds data-owner-id="42"
delete heading.dataset.collapsed; // removes the attribute
Values are always strings: convert with Number(...) as needed. Selectors can target them ([data-action="delete"]), which makes them ideal hooks for JavaScript that won't break when designers rename CSS classes.
Element content
An element's content can be treated as text or as HTML:
// <p>Run the <em>installer</em>.</p>
p.textContent; // "Run the installer." (all text, tags removed)
p.innerHTML; // "Run the <em>installer</em>." (markup inside the element)
p.outerHTML; // "<p>Run the <em>installer</em>.</p>" (including the element itself)
textContent: the safe default
Setting textContent replaces all children with a single text node. Anything that looks like HTML is just characters:
const userName = '<img src=x onerror="stealCookies()">';
greeting.textContent = `Hello, ${userName}`; // displayed literally; nothing runs
innerText is similar but layout-aware. It ignores hidden elements and applies CSS line breaks, and reading it forces a layout calculation, so it's slower. Prefer textContent unless you need the "as rendered" text.
innerHTML: powerful and dangerous
Setting innerHTML runs the HTML parser and replaces the element's children with the result:
list.innerHTML = "<li>Green</li><li>Black</li>"; // fine: the markup is your own
Never put untrusted data into innerHTML, including user input, URL parameters and API responses. That's how cross-site scripting (XSS) happens: the string from the previous example would create an <img> whose onerror handler runs attacker code in your page, with access to everything your users can do. Options when you need HTML built from data:
- Build the elements with DOM methods and set text with
textContent(below). - Escape the data first with a helper, or use a tagged template that escapes (article 16).
- For HTML that really must be rendered, sanitize it with a library such as DOMPurify. Browsers are also adding a built-in Sanitizer API (
element.setHTML(html)), so check its support before relying on it.
Two more caveats: innerHTML += "..." re-serializes and re-parses the whole content, which destroys existing elements along with their listeners and state; and <script> tags inserted via innerHTML never run.
outerHTML assignment replaces the element itself. insertAdjacentHTML(position, html) parses markup and inserts it without touching existing content, at one of four positions:

list.insertAdjacentHTML("beforeend", "<li>Oolong</li>"); // same XSS rules apply
Creating and inserting nodes
document.createElement(tag) makes a new, detached element. Configure it, then insert it:
const item = document.createElement("li");
item.className = "product";
item.dataset.id = "4";
item.textContent = "Jasmine";
list.append(item);
The modern insertion methods accept any number of nodes or strings (strings become text nodes, never HTML):
| Method | Inserts |
|---|---|
parent.append(...nodes) / parent.prepend(...nodes) | as the last / first children |
el.before(...nodes) / el.after(...nodes) | as siblings before / after el |
el.replaceWith(...nodes) | in place of el |
parent.replaceChildren(...nodes) | as the new set of children (no arguments empties the element) |
el.remove() | removes el from the tree |
list.prepend("Our teas:"); // a text node
list.firstElementChild.after(Object.assign(document.createElement("li"), { textContent: "Matcha" }));
list.querySelector('[data-id="3"]').replaceWith(soldOutNotice);
list.replaceChildren(); // empty the list
Older code uses appendChild, insertBefore, replaceChild and removeChild on the parent. They still work, but each takes only one node.
Inserting a node that's already in the document moves it. A node can only be in one place, so list.append(list.firstElementChild) moves the first item to the end. To duplicate a node, clone it: node.cloneNode(true) copies the element and all descendants (false copies only the element). Clones don't copy event listeners added with addEventListener, and you should change any duplicated id.
Building many nodes efficiently
Each insertion into the live document can trigger style and layout work, so when adding many nodes, build them first and insert once. A DocumentFragment is a lightweight, detached container: appending it moves its children into the target and leaves the fragment empty. Passing several nodes to append does the same job:
const fragment = document.createDocumentFragment();
for (const name of ["Assam", "Darjeeling", "Earl Grey"]) {
const li = document.createElement("li");
li.textContent = name;
fragment.append(li);
}
list.append(fragment); // one insertion
Templates
The <template> element holds inert markup: the browser parses it, but nothing inside is rendered, loaded or run. Its content property is a DocumentFragment you can clone and fill in:
<template id="row">
<li class="item"><span class="label"></span> <button class="remove">Remove</button></li>
</template>
const template = document.querySelector("#row");
for (const label of ["Milk", "Tea"]) {
const row = template.content.cloneNode(true);
row.querySelector(".label").textContent = label; // data goes in as text: XSS-safe
list.append(row);
}
Templates keep the markup in HTML, where it's easy to edit, while all data is inserted safely as text. They're also the basis of web components (article 113).
Example: generating a table of contents
Putting it together: scan the headings of an article, give each one an id if it lacks one, and build a linked outline:
function buildToc(article, container) {
const list = document.createElement("ol");
article.querySelectorAll("h2, h3").forEach((heading, index) => {
heading.id ||= `section-${index + 1}`; // keep existing ids
const link = document.createElement("a");
link.href = `#${heading.id}`;
link.textContent = heading.textContent;
const item = document.createElement("li");
item.className = heading.tagName.toLowerCase(); // "h2" or "h3", for indentation in CSS
item.append(link);
list.append(item);
});
container.replaceChildren(list);
}
buildToc(document.querySelector("article"), document.querySelector("#toc"));
// #toc now contains:
// <ol><li class="h2"><a href="#section-1">Install</a></li><li class="h3"><a href="#section-2">On macOS</a></li>...</ol>
querySelectorAll("h2, h3") returns the headings in document order, which is exactly the order a table of contents needs.
Common questions
Should I use element properties or setAttribute?
Properties for standard attributes: they're typed and convenient. setAttribute/getAttribute for custom attributes, ARIA attributes (aria-expanded) and when you need the exact attribute string. Use removeAttribute to remove one.
Is innerHTML always bad?
No. It's fine, and fast, for markup that you write yourself. It's dangerous only when any part of the string comes from users or other untrusted sources. Then use textContent, DOM building, templates or a sanitizer.
Why did my event listeners stop working after I updated the list?
Assigning innerHTML (or innerHTML +=) destroys the old elements and creates new ones, so listeners on the old elements are gone. Use event delegation on a stable parent (article 108), or insert new nodes without replacing existing ones.
What's the difference between remove() and removeChild()?
el.remove() removes the element itself. parent.removeChild(child) is the older form, called on the parent. Both detach the node; it can be inserted again later.
Summary
- Standard attributes are typed properties (
src,checked,maxLength,className,htmlFor); use the*Attributemethods for raw, custom or ARIA attributes and for removal. valueis the current state of a form field;defaultValueand the attribute are its initial value.classListmanages individual classes;datasetmapsdata-*attributes to camelCase properties.textContentsets text safely;innerHTMLparses HTML and must never receive untrusted data (XSS).- Create with
createElement; insert withappend,prepend,before,after,replaceWith,replaceChildren; remove withremove(). Inserting an existing node moves it. - Batch insertions with a DocumentFragment, and stamp out markup with
<template>andcloneNode(true).
Practice Questions
Rewrite this safely.
comments.innerHTML += `<li>${comment.text}</li>`;
Answer
const li = document.createElement("li");
li.textContent = comment.text;
comments.append(li);
This treats the comment as plain text, so no HTML in it can run, and it doesn't rebuild the existing list items.
After the user types "hello" into <input id="q" value="tea">, what do q.value and q.getAttribute("value") return?
Answer
"hello" and "tea". The property holds the current value; the attribute (and defaultValue) keeps the initial one.
How do you read <div data-user-id="42"> as a number?
Answer
Number(div.dataset.userId). Dataset names are camelCased, and the values are always strings.
What happens to #a, and why?
const a = document.querySelector("#a");
document.querySelector("#b").append(a);
Answer
#a moves to become the last child of #b. A node can only be in one place, so inserting an existing node moves it. Use a.cloneNode(true) to copy it instead.
Previous: Selecting and Traversing the DOM: querySelector, closest, matches and Node Relationships

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.