DOM Content Management

By Syncfusion®, Inc. · Last updated

Reading and changing content with innerHTML, textContent and outerHTML, adding, replacing and removing HTML, and working with attributes, properties and form attributes through getAttribute, setAttribute, removeAttribute and hasAttribute.

What Is DOM Content Management?

Every element has content (what is between its tags) and attributes (name="value" settings in its opening tag).

  • textContent = plain text only. Safe for anything users type.
  • innerHTML = HTML markup. Tags become real elements.
  • getAttribute(), setAttribute(), removeAttribute(), hasAttribute() manage attributes.

Simple lesson: use textContent for text, innerHTML only for markup you wrote yourself.

A Real-World Example

A product page shows a customer review. If the review goes into innerHTML, a review with <img onerror="..."> could run code on everyone's page. With textContent, the same review just shows as harmless text.

"Hi, <strong>Asha</strong>"

textContent Hi, <strong>Asha</strong>

innerHTML Hi, Asha

textContent keeps tags as text. innerHTML turns them into elements.

Each box is a small live page. Change the strings and run them again.

What You Will Learn

  1. innerHTML, textContent and outerHTML.
  2. Adding, replacing, removing and changing content safely.
  3. Reading, changing, adding and removing attributes.
  4. Attributes versus properties, and form attributes.
  5. The four attribute methods and their traps.

HTML manipulation

Changing what is inside an element after load: a new total, a warning, a fresh list.

innerHTML

The HTML inside an element, as a string. Setting it replaces the children, and tags become real elements.

innerHTML reads the markup inside an element, and setting it builds new elements

<p id="order">Order 1001 for <strong>Asha</strong></p>
<script>
  const order = document.getElementById("order");
  console.log("read:", order.innerHTML);

  order.innerHTML = "Order 1001 for <strong>Asha</strong>, <em>shipped</em>";
  console.log("after setting:", order.innerHTML);
  console.log("elements inside now:", order.children.length);
</script>

Expected output:

read: Order 1001 for <strong>Asha</strong>
after setting: Order 1001 for <strong>Asha</strong>, <em>shipped</em>
elements inside now: 2

textContent

Only the text, all tags stripped. Setting it puts in plain text: angle brackets show as characters.

The same string, set with textContent and with innerHTML

<p id="as-text">before</p>
<p id="as-html">before</p>
<script>
  const message = "Welcome, <strong>Asha</strong>";

  document.getElementById("as-text").textContent = message;
  document.getElementById("as-html").innerHTML = message;

  console.log("as text, the reader sees:", document.getElementById("as-text").textContent);
  console.log("as html, the reader sees:", document.getElementById("as-html").textContent);
  console.log("elements made from text:", document.getElementById("as-text").children.length);
  console.log("elements made from html:", document.getElementById("as-html").children.length);
</script>

Expected output:

as text, the reader sees: Welcome, <strong>Asha</strong>
as html, the reader sees: Welcome, Asha
elements made from text: 0
elements made from html: 1

Never put user-typed or server text into innerHTML. <img src="x" onerror="..."> would run code with full access to the page. This attack is cross-site scripting. Use textContent.

Why "textContent"? It gives the element's text content, and nothing else.

outerHTML

The element's own tag plus its inside. Setting it replaces the whole element; old variables point at the removed one.

outerHTML includes the element itself, and setting it replaces the element

<div id="card"><p>Order 1001 for Asha</p></div>
<script>
  const card = document.getElementById("card");
  console.log("innerHTML:", card.innerHTML);
  console.log("outerHTML:", card.outerHTML);

  card.outerHTML = '<section id="card">Order 1001, shipped</section>';

  console.log("old variable still on the page?", card.isConnected);
  console.log("what the page has now:", document.getElementById("card").outerHTML);
</script>

Expected output:

innerHTML: <p>Order 1001 for Asha</p>
outerHTML: <div id="card"><p>Order 1001 for Asha</p></div>
old variable still on the page? false
what the page has now: <section id="card">Order 1001, shipped</section>

Adding HTML dynamically

insertAdjacentHTML("beforeend", markup) adds markup and keeps the existing elements. innerHTML += looks the same but rebuilds every child.

insertAdjacentHTML keeps the existing items, and innerHTML += rebuilds them

<ul id="safe"><li id="first-safe">Order 1001</li></ul>
<ul id="rebuilt"><li id="first-rebuilt">Order 1001</li></ul>
<script>
  const firstSafe = document.getElementById("first-safe");
  document.getElementById("safe").insertAdjacentHTML("beforeend", "<li>Order 1002</li>");
  console.log("insertAdjacentHTML kept the old item?", firstSafe.isConnected);

  const firstRebuilt = document.getElementById("first-rebuilt");
  document.getElementById("rebuilt").innerHTML += "<li>Order 1002</li>";
  console.log("innerHTML += kept the old item?", firstRebuilt.isConnected);

  console.log("items in each list:",
    document.getElementById("safe").children.length,
    document.getElementById("rebuilt").children.length);
</script>

Expected output:

insertAdjacentHTML kept the old item? true
innerHTML += kept the old item? false
items in each list: 2 2

Positions: "beforebegin" and "afterend" (outside, as neighbours), "afterbegin" and "beforeend" (inside). insertAdjacentText() takes the same positions for plain text.

Replacing HTML

Set innerHTML (markup) or textContent (text) to swap all of an element's content in one step.

Replacing everything inside an order card

<div id="card">
  <h3>Order 1001</h3>
  <p>Status: packing</p>
</div>
<script>
  const card = document.getElementById("card");
  console.log("children before:", card.children.length);

  card.innerHTML = "<h3>Order 1001</h3><p>Status: shipped</p><p>Courier: FastShip</p>";
  console.log("children after:", card.children.length);
  console.log("last line now:", card.lastElementChild.textContent);
</script>

Expected output:

children before: 2
children after: 3
last line now: Courier: FastShip

Removing HTML

Empty an element but keep it: innerHTML = "", textContent = "", or replaceChildren() (clearest).

Three ways to empty an element, and the element stays on the page

<ul id="one"><li>Order 1001</li><li>Order 1002</li></ul>
<ul id="two"><li>Order 1003</li></ul>
<ul id="three"><li>Order 1004</li></ul>
<script>
  document.getElementById("one").innerHTML = "";
  document.getElementById("two").textContent = "";
  document.getElementById("three").replaceChildren();

  for (const id of ["one", "two", "three"]) {
    const list = document.getElementById(id);
    console.log(id, "has", list.children.length, "items and is still on the page:", list.isConnected);
  }
</script>

Expected output:

one has 0 items and is still on the page: true
two has 0 items and is still on the page: true
three has 0 items and is still on the page: true

Changing HTML content

Read, work out a new value, write back. Text from the page is a string, so convert with Number() before maths.

A counter read from the page is text until you convert it

<p>Items in basket: <span id="count">2</span></p>
<script>
  const count = document.getElementById("count");

  console.log("value read:", count.textContent, "| type:", typeof count.textContent);
  console.log("adding 1 to the text:", count.textContent + 1);

  count.textContent = Number(count.textContent) + 1;
  console.log("after converting first:", count.textContent);
</script>

Expected output:

value read: 2 | type: string
adding 1 to the text: 21
after converting first: 3

Attributes

An attribute is a name="value" setting in the opening tag, like href or title in <a href="/orders" title="All orders">.

Reading attributes

getAttribute(name) returns the written value as a string, or null if missing.

getAttribute returns the written value as a string, or null

<a id="link" href="/orders/1001" title="Order for Asha">Order 1001</a>
<script>
  const link = document.getElementById("link");

  console.log("href:", link.getAttribute("href"));
  console.log("title:", link.getAttribute("title"));
  console.log("target:", link.getAttribute("target"));
</script>

Expected output:

href: /orders/1001
title: Order for Asha
target: null

Changing attributes

setAttribute(name, value) gives an attribute a new value: a new link, a new image.

setAttribute changes where a link points and which image is shown

<a id="link" href="/orders/1001">View order</a>
<img id="photo" src="asha.png" alt="Asha">
<script>
  const link = document.getElementById("link");
  const photo = document.getElementById("photo");

  link.setAttribute("href", "/orders/1002");
  photo.setAttribute("src", "ravi.png");
  photo.setAttribute("alt", "Ravi");

  console.log(link.outerHTML);
  console.log(photo.outerHTML);
</script>

Expected output:

<a id="link" href="/orders/1002">View order</a>
<img id="photo" src="ravi.png" alt="Ravi">

Adding attributes

setAttribute() creates the attribute if it does not exist: title, aria-label, data-*.

setAttribute adds attributes that were not in the markup

<button id="ship">Ship</button>
<script>
  const ship = document.getElementById("ship");
  console.log("before:", ship.outerHTML);

  ship.setAttribute("title", "Ship order 1001 today");
  ship.setAttribute("aria-label", "Ship order 1001");
  ship.setAttribute("data-order-id", "1001");

  console.log("after:", ship.outerHTML);
</script>

Expected output:

before: <button id="ship">Ship</button>
after: <button id="ship" title="Ship order 1001 today" aria-label="Ship order 1001" data-order-id="1001">Ship</button>

Removing attributes

removeAttribute(name) takes it out. Boolean attributes like disabled are on whenever they are present, even with the value "false".

A boolean attribute set to false still counts, so it has to be removed

<button id="pay" disabled>Pay now</button>
<script>
  const pay = document.getElementById("pay");
  console.log("disabled at the start?", pay.disabled);

  pay.setAttribute("disabled", "false");
  console.log("after setting it to false?", pay.disabled);

  pay.removeAttribute("disabled");
  console.log("after removing it?", pay.disabled);
  console.log(pay.outerHTML);
</script>

Expected output:

disabled at the start? true
after setting it to false? true
after removing it? false
<button id="pay">Pay now</button>

Attributes vs properties

  • Attribute: what the HTML says (the starting value).
  • Property: the live value on the object, like input.value.
  • class is reached through the className property (class is a reserved word).

The value attribute is the starting value, and the value property is the current one

<input id="customer" value="Asha">
<script>
  const input = document.getElementById("customer");
  console.log("attribute:", input.getAttribute("value"), "| property:", input.value);

  // This is what happens when a user types a new name.
  input.value = "Ravi";

  console.log("attribute:", input.getAttribute("value"), "| property:", input.value);
  console.log("markup still says:", input.outerHTML);
</script>

Expected output:

attribute: Asha | property: Asha
attribute: Asha | property: Ravi
markup still says: <input id="customer" value="Asha">

Use the property when there is one (input.value, checkbox.checked, button.disabled, element.id). Use getAttribute/setAttribute for the rest, like aria-label and data-*.

Why "property"? It belongs to the JavaScript object, like any object's properties.

Working with form attributes

placeholder (grey hint), required (must be filled), type, and a checkbox's checked property.

Reading and changing the attributes of three form fields

<input id="email" type="email" placeholder="you@example.com">
<input id="gift" type="checkbox">
<select id="delivery">
  <option value="standard">Standard</option>
  <option value="express" selected>Express</option>
</select>
<script>
  const email = document.getElementById("email");
  const gift = document.getElementById("gift");
  const delivery = document.getElementById("delivery");

  console.log("placeholder:", email.placeholder);
  console.log("required at first?", email.required);
  email.required = true;
  console.log("required now?", email.required, "| attribute added?", email.hasAttribute("required"));

  console.log("gift ticked?", gift.checked);
  gift.checked = true;
  console.log("gift ticked now?", gift.checked);

  console.log("delivery choice:", delivery.value);
  delivery.value = "standard";
  console.log("delivery choice now:", delivery.value);
</script>

Expected output:

placeholder: you@example.com
required at first? false
required now? true | attribute added? true
gift ticked? false
gift ticked now? true
delivery choice: express
delivery choice now: standard

Key methods

getAttribute()

Always a string (or null), even for numbers. "24" + 1 is "241", and "false" is truthy.

getAttribute always hands back a string

<li id="order" data-seats="24" data-express="false">Order 1001</li>
<script>
  const order = document.getElementById("order");
  const seats = order.getAttribute("data-seats");
  const express = order.getAttribute("data-express");

  console.log("seats:", seats, "| type:", typeof seats);
  console.log("seats plus 1 as text:", seats + 1);
  console.log("seats plus 1 as a number:", Number(seats) + 1);
  console.log("is the string \"false\" truthy?", Boolean(express));
</script>

Expected output:

seats: 24 | type: string
seats plus 1 as text: 241
seats plus 1 as a number: 25
is the string "false" truthy? true

setAttribute()

Every value is turned into text before it is stored.

setAttribute turns every value into text

<li id="order">Order 1001</li>
<script>
  const order = document.getElementById("order");

  order.setAttribute("data-total", 450);
  order.setAttribute("data-paid", true);

  console.log("total:", order.getAttribute("data-total"), typeof order.getAttribute("data-total"));
  console.log("paid:", order.getAttribute("data-paid"), typeof order.getAttribute("data-paid"));
  console.log(order.outerHTML);
</script>

Expected output:

total: 450 string
paid: true string
<li id="order" data-total="450" data-paid="true">Order 1001</li>

removeAttribute()

Deletes an attribute. A missing one is quietly ignored, no error.

removeAttribute takes an attribute out, and ignores one that is missing

<input id="coupon" placeholder="Coupon code" disabled>
<script>
  const coupon = document.getElementById("coupon");

  coupon.removeAttribute("disabled");
  coupon.removeAttribute("maxlength");

  console.log("disabled now?", coupon.disabled);
  console.log(coupon.outerHTML);
</script>

Expected output:

disabled now? false
<input id="coupon" placeholder="Coupon code">

hasAttribute()

true or false: the right test for boolean attributes. (getAttribute("disabled") can be "", which is falsy.)

hasAttribute checks presence, which is what a boolean attribute means

<button id="save" disabled>Save</button>
<button id="cancel">Cancel</button>
<script>
  for (const button of document.querySelectorAll("button")) {
    console.log(button.id, "has disabled?", button.hasAttribute("disabled"),
      "| value:", JSON.stringify(button.getAttribute("disabled")));
  }
</script>

Expected output:

save has disabled? true | value: ""
cancel has disabled? false | value: null

Content on a Web Page

The review box shows typed text safely with textContent. The data-rating attribute stores the stars, read back with getAttribute() and converted with Number().

Showing reviews safely with textContent

const box = document.querySelector("#notices");
const input = document.createElement("input");
input.value = 'Great bottle! <img src="x" onerror="alert(1)">';
const stars = document.createElement("select");
stars.innerHTML = "<option>5</option><option>4</option><option>3</option>";
const add = document.createElement("button");
add.textContent = "Add review";
const list = document.createElement("div");
box.append(input, stars, add, list);

add.addEventListener("click", () => {
  const review = document.createElement("p");
  review.textContent = input.value;
  review.setAttribute("data-rating", stars.value);
  list.prepend(review);

  const ratings = [...list.querySelectorAll("p")].map((p) => Number(p.getAttribute("data-rating")));
  const average = ratings.reduce((sum, r) => sum + r, 0) / ratings.length;
  console.log(`reviews: ${ratings.length}, average: ${average.toFixed(1)}, images created: ${list.querySelectorAll("img").length}`);
});

Press Add review. The <img> tag shows as text, and images created: 0 proves no element was made.

Easy way to remember: textContent for text from people; innerHTML only for HTML you wrote.

TL;DR

  • textContent = safe plain text; innerHTML = markup; outerHTML = the element itself too.
  • Add with insertAdjacentHTML, not innerHTML +=.
  • Values from the page and from attributes are strings; convert before maths.
  • Boolean attributes: present means on; remove them to switch off.
  • Prefer properties (value, checked, disabled); use attribute methods for the rest.

Try this

In the textContent box, use "Welcome, <em>Ravi</em>". The first paragraph shows the tags as characters; the second shows Ravi in italics with one element inside.

Check Yourself

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
User text into innerHTMLText is always harmlessIt is read as markupCode can run on the page
count.textContent + 1Page numbers are numbersThey are strings; use Number()"21" instead of 3
innerHTML += to add itemsIt only addsIt rebuilds every childClick handlers are lost
setAttribute("disabled", "false")"false" switches it offPresence switches it onThe button stays disabled
getAttribute("value") for typed textThe attribute follows typingRead input.valueYou see the starting value
Using a variable after setting outerHTMLIt still points at the pageThe element was replacedChanges go nowhere

Quick reference

SyntaxMeaning
el.innerHTMLthe HTML inside the element; setting it replaces the children with parsed markup
el.textContentthe text inside the element; setting it puts in plain text
el.outerHTMLthe element itself plus its inside; setting it replaces the element
el.insertAdjacentHTML("beforeend", html)add markup at the end of the inside, keeping existing children
el.innerHTML = "" / el.replaceChildren()remove everything inside the element
el.getAttribute("href")the attribute's value as a string, or null if it is missing
el.setAttribute("href", "/orders")change the attribute, or add it if it is missing
el.removeAttribute("disabled")take the attribute out of the tag
el.hasAttribute("disabled")true if the attribute is present, otherwise false
input.value / checkbox.checkedthe current state of a form field, as a property

Exercises

What to Remember

  • textContent for text, innerHTML for your own markup.
  • Everything read from the page is a string.
  • Properties for live values; attributes for the written HTML.

Next: DOM Styling. Change how elements look with inline styles and classList.