# DOM Content Management

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: DOM Manipulation
Source: https://www.devtutorials.ai/learn/javascript/dom/dom-content-management

> 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.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="The same string goes into two boxes. Through textContent it appears as plain characters. Through innerHTML the tags turn into a bold word." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="150" y="14" width="260" height="30" rx="6" fill="#fefce8" stroke="#ca8a04" />
    <text x="280" y="34" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#854d0e">"Hi, &lt;strong&gt;Asha&lt;/strong&gt;"</text>
    <line x1="230" y1="44" x2="140" y2="80" stroke="#94a3b8" strokeWidth="2" /><line x1="330" y1="44" x2="420" y2="80" stroke="#94a3b8" strokeWidth="2" />
    <rect x="30" y="80" width="220" height="66" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="140" y="102" textAnchor="middle" fontSize="12" fill="#166534">textContent</text>
    <text x="140" y="128" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#166534">Hi, &lt;strong&gt;Asha&lt;/strong&gt;</text>
    <rect x="310" y="80" width="220" height="66" rx="8" fill="#fee2e2" stroke="#dc2626" />
    <text x="420" y="102" textAnchor="middle" fontSize="12" fill="#991b1b">innerHTML</text>
    <text x="420" y="128" textAnchor="middle" fontSize="14" fill="#991b1b">Hi, <tspan fontWeight="bold">Asha</tspan><animate attributeName="opacity" values="0.3;1;0.3" dur="2s" repeatCount="indefinite" /></text>
  </svg>
  <figcaption>textContent keeps tags as text. innerHTML turns them into elements.</figcaption>
</figure>

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**.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

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

### Removing HTML

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

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
<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-*`.

```dom runnable title="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:

```text
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"`.

```dom runnable title="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:

```text
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).

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.)

```dom runnable title="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:

```text
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()`.

```js runnable preview="notices" title="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:** **text**Content for **text** from people; **inner**HTML 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

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| User text into `innerHTML` | Text is always harmless | It is read as markup | Code can run on the page |
| `count.textContent + 1` | Page numbers are numbers | They are strings; use `Number()` | `"21"` instead of `3` |
| `innerHTML +=` to add items | It only adds | It rebuilds every child | Click handlers are lost |
| `setAttribute("disabled", "false")` | `"false"` switches it off | Presence switches it on | The button stays disabled |
| `getAttribute("value")` for typed text | The attribute follows typing | Read `input.value` | You see the starting value |
| Using a variable after setting `outerHTML` | It still points at the page | The element was replaced | Changes go nowhere |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `el.innerHTML` | the HTML inside the element; setting it replaces the children with parsed markup |
| `el.textContent` | the text inside the element; setting it puts in plain text |
| `el.outerHTML` | the 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.checked` | the current state of a form field, as a property |

</div>

## 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`.
