Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 156 ยท The DOM

Changing Content

Change page content safely with textContent, innerText and innerHTML, avoid XSS, and learn attributes vs properties, boolean attributes and dataset.

Once you have an element, the next job is usually to change it: show a new total, update a status message, swap an image, mark a button as pressed. The DOM gives you several tools for this, and picking the right one is partly about convenience and partly about security.

This lesson covers the three text-and-HTML properties (textContent, innerText and innerHTML), the safer ways to insert HTML, and then attributes: how to read and write them, how they differ from properties, and how dataset gives you tidy access to data-* attributes. The HTML course introduced some of these in The Document Object Model; here you will see what happens underneath.

textContent: plain text in and out

textContent is the property you will use most. Reading it returns all the text inside an element, including text in its descendants, joined together. Writing it removes every child of the element and replaces them with a single text node.

Whatever you assign is treated as literal characters. A string like "<b>Hi</b>" shows up on the page with the angle brackets visible. That makes textContent safe for any value, including things a user typed.

JavaScript
const status = document.querySelector("#status");
status.textContent = `Saved ${count} items`;   // safe for any value
console.log(status.textContent);                // read it back

innerText: text as the user sees it

innerText looks similar but is aware of CSS. When reading, it returns the text as rendered: hidden elements are left out, text-transform is applied and line breaks follow the layout. To compute that, the browser has to calculate styles and layout, which makes innerText slower.

textContent vs innerText

textContent includes the hidden note and all the raw whitespace from the source. innerText shows what a reader would see. A good rule: use textContent unless you specifically need the rendered text, for example to copy what is visible.

innerHTML: parsing strings as HTML

innerHTML reads an element's content as an HTML string, and writing it parses your string into new nodes. That is convenient for markup you wrote yourself, but it has three costs.

  1. Security. If any part of the string comes from outside your code โ€” a form field, a URL parameter, an API response โ€” an attacker can inject HTML that runs JavaScript in your page. This is cross-site scripting (XSS). A name like <img src=x onerror="..."> executes the moment it is parsed.
  2. It destroys existing nodes. Assigning innerHTML throws away all children and builds new ones. Any listeners, typed input or state on the old elements are gone.
  3. Hidden re-parsing. el.innerHTML += "<li>โ€ฆ</li>" looks like it appends, but it serializes the whole content to a string, adds yours and re-parses everything.

The second point catches people constantly:

innerHTML += breaks listeners

Click the first button: its listener runs. Add an item, then click the first button again. Nothing happens โ€” it is a new button parsed from a string, and the listener was attached to the old one, which no longer exists.

Treat innerHTML with outside data as a bug. Use textContent for text and build elements with createElement() (see Creating and Removing Elements). If you truly must render HTML from an outside source, it has to be cleaned by a trusted sanitizer library first. Browsers are adding a built-in option, element.setHTML(), which sanitizes as it inserts, but it is new and not yet available in every browser, so check support before relying on it.

Adding without replacing: insertAdjacentHTML() and friends

When you want to add some of your own markup next to existing content without destroying it, use insertAdjacentHTML(position, html). The position is one of four strings:

  • "beforebegin" โ€” before the element itself
  • "afterbegin" โ€” inside, before its first child
  • "beforeend" โ€” inside, after its last child
  • "afterend" โ€” after the element itself
JavaScript
list.insertAdjacentHTML("beforeend", "<li>New item</li>"); // existing items untouched

The same rule applies: only pass HTML you control. Its sibling insertAdjacentText() inserts plain text at those positions and is always safe.

outerHTML is the last of the family: it is like innerHTML but includes the element's own tag. Reading it is handy for debugging; assigning to it replaces the whole element.

Attributes

Attributes are the name="value" pairs written in HTML. Four methods handle any attribute by name:

  • getAttribute(name) โ€” the value as a string, or null if the attribute is absent.
  • setAttribute(name, value) โ€” adds or changes it; the value is converted to a string.
  • removeAttribute(name) โ€” removes it.
  • hasAttribute(name) โ€” true or false.
  • toggleAttribute(name, force?) โ€” adds or removes it, and returns whether it is now present.

Properties vs attributes

Most standard attributes are also reflected as properties on the element object: img.alt, a.href, input.disabled, el.id. Usually, reading or writing either one gives the same result, but there are important differences:

  • Types. Attributes are always strings. Properties have proper types: input.disabled is a boolean, input.maxLength a number, a.href a full URL.
  • Names. A few properties have different names because the attribute name is a reserved word or awkward: class โ†’ className, for โ†’ htmlFor, tabindex โ†’ tabIndex.
  • Resolved values. a.getAttribute("href") returns what you wrote, like "/pricing"; a.href returns the resolved absolute URL.
  • Current state vs initial state. For form fields, the value attribute is the field's starting value. The value property is what is in the field now. Typing changes the property, never the attribute. The same goes for checked. The initial values are still available as defaultValue and defaultChecked.
value: attribute vs property

Type a different city, tick the box and click Compare. The property follows what you did; the attribute still holds the original HTML.

Boolean attributes

Boolean attributes like disabled, hidden, required and checked are on when present and off when absent, whatever their value. That leads to a classic bug:

JavaScript
button.setAttribute("disabled", "false"); // still disabled! The attribute is present.
button.disabled = false;                  // correct: removes the attribute

Prefer the boolean property, or use toggleAttribute("disabled", isBusy). Note that ARIA attributes are different: aria-expanded and aria-pressed really do take the strings "true" and "false".

dataset and data-* attributes

Custom data belongs in data-* attributes (see Custom Data Attributes). The dataset property maps them to an object, converting kebab-case names to camelCase:

HTML attribute JavaScript
data-id="17" el.dataset.id
data-unit-price="4.5" el.dataset.unitPrice
data-in-stock el.dataset.inStock (empty string "")

Values are always strings, so convert them when you need numbers. Assigning a property creates or updates the attribute, and delete el.dataset.name removes it.

A dataset-driven price tag

Because data-on-sale is a real attribute, the CSS attribute selector picks it up immediately. Storing state this way keeps your JavaScript and your styles in sync without extra code. The next lesson, Styles and Classes, takes that idea further.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A visitor's display name must appear in a greeting. Which line is safe?

    textContent never parses HTML, so a malicious name is shown as harmless text. The other three parse the string as HTML and allow XSS.
  2. 2. Why does list.innerHTML += "<li>โ€ฆ</li>" break click listeners on existing items?

    The content is serialized, combined and re-parsed. The new elements look the same but are different objects without listeners.
  3. 3. A user types "Oslo" into <input value="Rome">. What does input.getAttribute("value") return?

    The value attribute holds the starting value. The value property (input.value) holds what is currently typed: "Oslo".
  4. 4. What does button.setAttribute("disabled", "false") do?

    Boolean attributes are on whenever they are present. Use button.disabled = false or removeAttribute("disabled").
  5. 5. How do you read data-max-guests="6" as a number?

    dataset converts kebab-case to camelCase, and values are always strings, so convert with Number().

Summary

  • textContent reads and writes plain text and is always safe; innerText returns the rendered, CSS-aware text and is slower.
  • innerHTML parses HTML: never feed it outside data, and remember that assigning it replaces existing nodes and their listeners.
  • insertAdjacentHTML() and insertAdjacentText() add content at one of four positions without destroying what is there.
  • Attributes are strings in the HTML; properties are typed, sometimes renamed, and for form fields reflect the current state.
  • Boolean attributes are on when present: use the boolean property or toggleAttribute().
  • dataset maps data-* attributes to camelCase string properties.

Next: Styles and Classes โ€” classList, inline styles, CSS variables and computed styles.