Thuta Learning
JavaScript
IntermediateProgrammingBeginner

Modify Elements

JavaScriptLesson 2625 min

What you'll walk away with

  • Explain the difference between textContent, innerText and innerHTML, and choose textContent for user input
  • Switch visual state with classList.add, remove and toggle
  • Use setAttribute, dataset and style properties correctly
  • Render a list from a data array repeatedly with createElement and replaceChildren

Explain it simply

Explain it simply

Once you have found an element, you can change it. Think of a shop sign: you can change its words (textContent), stick on or peel off coloured labels (classList), write notes on the back (attributes and dataset), or make brand-new signs and hang them up (createElement and append).

The most important rule: never insert text a user typed as HTML. textContent shows text as text, while innerHTML interprets that same text as markup.

Problem → Why → Solution

The problem: a comment box that lets anyone run code

Code that shows comments with innerHTML += looks simple and seems to work. Then one user submits <img src=x onerror="..."> as a comment. The browser builds a real img element, the image fails to load, and the JavaScript inside onerror runs, in the browser of everyone who views the comment. On top of that, += rebuilds the whole list on every call, so the existing elements lose their event listeners.

comments-unsafe.js
const commentList = document.getElementById("comments");

function addComment(author, text) {
  // DANGER: user text is parsed as HTML
  commentList.innerHTML += "<li><b>" + author + "</b>: " + text + "</li>";
}

addComment("Mya", "Great article!");
addComment("attacker", '<img src=x onerror="stealCookies()">'); // runs code

Why is this dangerous?

innerHTML hands the string to the HTML parser, so tags and event-handler attributes inside it become real elements. This is called cross-site scripting (XSS). The fix is to build elements with createElement and put user text in with textContent, which parses nothing, so <img ...> appears as plain characters.

Core concept: pick the tool that matches the change

What you want to changeTool to use
Text, including user inputelement.textContent
Trusted HTML you wrote yourselfelement.innerHTML
Visual state (active, hidden, error)element.classList
Attributes (title, href, aria-*)setAttribute() or the property
Custom dataelement.dataset
New elementscreateElement() + append()

textContent removes all of an element's children and puts a single text node in their place; it parses nothing, so it is fast and safe. innerHTML parses its string as HTML, which is fine for static markup you wrote yourself and dangerous once user data is mixed in. innerText resembles textContent but takes CSS into account: it leaves out text hidden with display: none, and reading it can force a layout calculation, so it is slower.

To change how an element looks, prefer defining classes such as .error or .hidden in CSS and switching them with classList.add(), remove() and toggle() over editing inline styles like style.color. CSS keeps control of the design while JavaScript only changes state. Passing a force argument, as in toggle("hidden", condition), adds the class when the condition is true and removes it when false. When you do use style, property names are camelCase (fontSize, backgroundColor) and values are strings with units such as px.

Attributes and properties are not always the same thing. An input's value attribute is the initial value from the HTML, while the input.value property is what the user has typed right now, so getAttribute("value") keeps returning the original even after typing. For boolean attributes such as disabled, setAttribute("disabled", "false") still disables the button, because the attribute merely being present means true. Use button.disabled = false or removeAttribute("disabled") instead.

Create new elements with createElement(), insert them with append(), prepend(), before() or after(), and take them out with remove(). replaceChildren(...nodes) swaps all existing children for new ones in a single step, which makes it the best fit for re-rendering a list from data.

Mental model: data in, nodes built, page swapped
  1. Data is the single source of truth
  2. Build nodes with createElement
  3. Put user text in via textContent
  4. Swap them in with replaceChildren

Re-run one render function whenever the data changes, and the UI always matches the data.

General pattern

javascript
element.textContent = untrustedText;          // safe: never parsed as HTML
element.classList.toggle("state-class", isOn); // add or remove by condition
element.setAttribute("aria-label", labelText); // any attribute
element.dataset.someKey = "value";             // data-some-key="value"

const child = document.createElement("tag");
child.textContent = text;
parent.replaceChildren(...newChildren);        // swap all children at once

Use textContent for text, classList for state, and setAttribute or dataset for attributes. Build new elements with createElement and place them into the parent in one go with replaceChildren.

Example: updating a status message

This code creates the <p> it changes, so it runs in the console of a blank page. It changes the text, a class, an attribute, data and a style one at a time and inspects the result through outerHTML. Finally it shows that HTML-looking user input set through textContent never turns into an element.

modify-message.js
// Paste into the console of a blank page: it creates the <p> it changes.
const message = document.createElement("p");
message.id = "message";
message.textContent = "Old text";
document.body.append(message);

message.textContent = "Saved!";                 // text only, no HTML parsing
message.classList.add("notice");
message.classList.toggle("hidden");             // adds "hidden"
message.classList.toggle("hidden");             // removes it again
message.setAttribute("title", "Status message");
message.dataset.state = "saved";                // becomes data-state="saved"
message.style.color = "teal";

console.log(message.outerHTML);
console.log(message.classList.contains("hidden"));

const userInput = "<img src=x onerror=alert(1)>";
message.textContent = userInput;                // shown as text, never run
console.log(message.textContent);
console.log(message.children.length);           // 0: no <img> was created

Code breakdown

  1. Textmessage.textContent = "Saved!"; // text only, no HTML parsing

    Removes the "Old text" text node and puts "Saved!" in its place.

  2. Classesmessage.classList.toggle("hidden"); // adds "hidden"

    toggle() adds a missing class and removes a present one. Called twice, hidden ends up absent, contains("hidden") is false, and only notice remains.

  3. Attributes and datamessage.dataset.state = "saved"; // becomes data-state="saved"

    setAttribute("title", ...) adds a title attribute and dataset.state becomes a data-state attribute. outerHTML lists the attributes in the order they were added.

  4. Inline stylemessage.style.color = "teal";

    Writes color: teal; into the style attribute. Inline styles override the stylesheet, so prefer classes where you can.

  5. User input stays textconsole.log(message.children.length); // 0: no <img> was created

    textContent inserted <img ...> as characters, so there are no child elements and onerror never runs. With innerHTML this would be 1 and the code would run.

You should see
<p id="message" class="notice" title="Status message" data-state="saved" style="color: teal;">Saved!</p>
false
<img src=x onerror=alert(1)>
0

Creating, inserting and removing elements

append() adds at the end of a parent, prepend() at the start, and before() and after() insert siblings next to an element. All of them accept several nodes and also strings, which become text nodes. Appending a node that is already in the DOM moves it rather than copying it. When adding many items, collect them first and insert once with replaceChildren(...rows) or a DocumentFragment, so the browser recalculates layout only once.

In real projects

Where this shows up in real projects

UIs such as product lists, carts and notification panels usually have one render function that builds the DOM from a data array. Whether new data arrives from an API or the user deletes an item, you update the data and call render() again. When ten places in the code poke at the DOM directly, the UI and the data slowly drift apart and you get bugs like "the cart shows 3 items but holds 2". Frameworks such as React and Vue automate exactly this render-from-data idea.

Empty states ("Your cart is empty"), loading states and error states are decided in that same render function and shown with replaceChildren. Put every piece of user-written data, such as product names or review text, in through textContent. If you genuinely must display rich text, clean it first with a trusted sanitizer library such as DOMPurify.

Common mistakes

Common mistakes

1. Putting user input into innerHTML

Mixing user data into a template literal and assigning it to innerHTML opens an XSS hole. A <script> tag inserted through innerHTML does not run, but event-handler attributes such as onerror do. Build the element and use textContent instead.

2. Adding items one by one with innerHTML +=

list.innerHTML += "<li>...</li>" turns the existing HTML into a string, concatenates and reparses all of it. Besides being slow, every existing element is recreated, so event listeners and anything typed into inputs are lost. Use append() instead.

3. Writing style properties with CSS names

element.style.font-size = "20px" is a SyntaxError, and element.style.fontSize = 20 silently does nothing because the unit is missing. Write element.style.fontSize = "20px" with the camelCase name and a unit, or better, toggle a class.

Best practices

Best practices

  • Show and hide elements with the hidden attribute or a .hidden class rather than editing style.display.
  • When a button's state changes, update accessibility attributes such as aria-pressed or aria-expanded along with the visual class.
  • Keep DOM-changing code inside one or two render functions; event handlers should only change data and then call render.

Mini challenge

Mini challenge: render a cart from data

Write renderCart(items). Every call rebuilds the list from the data, and an empty cart shows an empty state. Your solution must create the elements it needs itself.

  • Create a <ul> and a status <p> and add them to body
  • For each item build an <li> with textContent "name xqty" and a data-id, inserted with replaceChildren
  • For an empty cart show a single "Your cart is empty" li with the class "empty"
  • Show "N item(s)" in the status and use classList.toggle to add "warning" when N is 0
  • A name like <b>Cake</b> must appear as plain text
render-cart.js
// TODO: create a <ul> and a status <p>, then append both to document.body

function renderCart(items) {
  // TODO: if items is empty, build one <li class="empty"> with the message
  // TODO: otherwise build one <li> per item ("Tea x2"), set dataset.id
  // TODO: swap the list's children in a single replaceChildren call
  // TODO: total the quantities, update the status text,
  //       and toggle the "warning" class when the total is 0
}

// TODO: render two items, then one item, then an empty cart,
//       logging the list size and status after each render

Expected: The console shows: 2 3 item(s) <b>Cake</b> x1 1 Tea x3 Your cart is empty warning

Show hint

Build an array of li elements with items.map(), then spread it: list.replaceChildren(...rows). classList.toggle("warning", count === 0) adds the class when count is 0 and removes it otherwise.

Show solution
render-cart.js
// Builds its own elements, so it works on any blank page.
const list = document.createElement("ul");
const status = document.createElement("p");
document.body.append(status, list);

function renderCart(items) {
  if (items.length === 0) {
    const empty = document.createElement("li");
    empty.textContent = "Your cart is empty";
    empty.classList.add("empty");
    list.replaceChildren(empty);
  } else {
    const rows = items.map((item) => {
      const li = document.createElement("li");
      li.textContent = `${item.name} x${item.qty}`;
      li.dataset.id = item.id;
      return li;
    });
    list.replaceChildren(...rows);
  }
  const count = items.reduce((sum, item) => sum + item.qty, 0);
  status.textContent = `${count} item(s)`;
  status.classList.toggle("warning", count === 0);
}

renderCart([
  { id: "p1", name: "Tea", qty: 2 },
  { id: "p2", name: "<b>Cake</b>", qty: 1 },
]);
console.log(list.children.length, status.textContent);
console.log(list.lastElementChild.textContent);

renderCart([{ id: "p1", name: "Tea", qty: 3 }]);
console.log(list.children.length, list.firstElementChild.textContent);

renderCart([]);
console.log(list.textContent, status.className);

Quick quiz 1 / 3

After p.textContent = "<b>Hi</b>";, what does the user see on the page?

Quick quiz 2 / 3

Which line correctly sets paragraph p's font size to 20px?

Quick quiz 3 / 3

render() adds three li elements with list.append(...rows). If render() runs twice with the same data, how many li elements does the list hold?

What to remember

  • Use textContent for text and user input; keep innerHTML for trusted HTML you wrote yourself.
  • Switch visual state with classList, set attributes with setAttribute and dataset, and give style camelCase names and unit strings.
  • Build nodes with createElement, insert them with append, before or after, and take them out with remove().
  • Re-render from data through one function and replaceChildren so the UI always matches the data.

MDN — Document Object Model (DOM) — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Modify Elements | Thuta Learning