Changing Content and Styles

Updated · 8 min read
mediumES2026javascriptdomtextcontentinnerhtmlxsssecurity

Once you have selected an element, you can change everything about it: its text, its HTML, its attributes, its classes, its styles and its data attributes. Most of these are simple property assignments. One of them, innerHTML, deserves special care: it turns a string into real HTML, and when that string contains anything a user typed, it opens the door to cross-site scripting (XSS), one of the most common web security holes. This lesson shows the safe way first.

In One Minute

  • element.textContent = text sets plain text. Safe for any input. Use it by default.
  • element.innerHTML = html parses a string as HTML. Never use it with user input.
  • Attributes: getAttribute, setAttribute, removeAttribute, hasAttribute; many also have properties (input.value, a.href, img.alt).
  • Classes: classList.add, remove, toggle, contains, replace. Prefer classes over inline styles.
  • data-* attributes are read and written through element.dataset.

Changing Text: textContent

textContent gets or sets the text of an element and all its descendants. When you set it, the string is inserted as text, never interpreted as HTML:

text-content.html
<p id="status">Loading...</p>
<script>
  const status = document.querySelector("#status");
  console.log(status.textContent);

  status.textContent = "Navika paid $120.";
  console.log(status.textContent);

  status.textContent = "<b>bold?</b>";
  console.log(status.innerHTML);
  console.log(status.children.length);
</script>
Output
Loading...
Navika paid $120.
&lt;b&gt;bold?&lt;/b&gt;
0

Explanation: setting textContent to "<b>bold?</b>" shows those characters literally on the page; no <b> element is created. The browser stores them escaped (&lt; is <), which is why innerHTML reads back the escaped form and the paragraph has no child elements.

PropertyGetsSets
textContentAll text, including hidden elementsPlain text (safe)
innerTextOnly text that is visible, as styledPlain text (safe), but triggers a layout calculation
innerHTMLThe HTML markup insideParses the string as HTML (dangerous with user input)
outerHTMLThe element's own markup tooReplaces the element (same danger)

Prefer textContent. innerText is slower because the browser must work out what is visible.

innerHTML and Cross-Site Scripting

Cross-site scripting (XSS) is an attack where someone gets their code to run in your page, in your users' browsers, with access to everything your page can do. The most common way in is inserting attacker-controlled text as HTML.

Imagine the Fee Tracker shows a student's name with innerHTML, and someone registers with this "name":

xss.html
<p id="welcome"></p>
<script>
  const nameFromForm = '<img src="x" onerror="console.log(\'Attacker code ran!\')">';

  document.querySelector("#welcome").innerHTML = `Welcome, ${nameFromForm}`;
</script>
Output
Attacker code ran!

Explanation: innerHTML created a real <img> element. Its image fails to load, so its onerror attribute runs as JavaScript. Here it only logs a message, but it could read the page, send the user's data to another server, or act as the user. (A <script> tag inserted with innerHTML doesn't run, but event handler attributes like onerror do, so that is no protection.)

The same code with textContent is completely safe:

xss-safe.html
<p id="welcome"></p>
<script>
  const nameFromForm = '<img src="x" onerror="console.log(\'Attacker code ran!\')">';

  document.querySelector("#welcome").textContent = `Welcome, ${nameFromForm}`;
  console.log(document.querySelector("#welcome").children.length);
</script>
Output
0

The page shows the odd name as plain text, and nothing runs.

innerHTML is fine for HTML you wrote yourself, with no outside data in it, such as resetting a container with list.innerHTML = "" or a fixed template.

Attributes and Properties

Attributes are written in HTML (<input type="number" value="120">). When the browser builds the DOM, many attributes become properties on the element object. They are related but not identical:

attributes.html
<a id="link" href="/fees">Fees</a>
<input id="amount" type="number" value="120">
<script>
  const link = document.querySelector("#link");
  console.log(link.getAttribute("href"));
  console.log(link.href.endsWith("/fees"));

  const input = document.querySelector("#amount");
  input.value = "85";
  console.log(input.value, input.getAttribute("value"));

  link.setAttribute("aria-current", "page");
  console.log(link.hasAttribute("aria-current"), link.getAttribute("aria-current"));
  link.removeAttribute("aria-current");
  console.log(link.hasAttribute("aria-current"));
</script>
Output
/fees
true
85 120
true page
false

Explanation:

  • getAttribute("href") returns exactly what the HTML says; the href property returns the full resolved URL (here the page's own address plus /fees, so the example checks only the end).
  • For inputs, the value property is the current value; the value attribute is only the starting value. After typing (or setting the property), they differ.
  • setAttribute, hasAttribute and removeAttribute work for any attribute, including ones without a property, such as ARIA attributes for accessibility.

Classes: classList

The cleanest way to change how an element looks is to add or remove CSS classes, keeping the styles in CSS. classList manages them:

class-list.html
<li id="row" class="fee">Books</li>
<script>
  const row = document.querySelector("#row");

  row.classList.add("unpaid", "highlight");
  console.log(row.className);

  row.classList.remove("highlight");
  console.log(row.classList.contains("unpaid"));

  row.classList.toggle("selected");
  console.log(row.className);
  row.classList.toggle("selected");

  row.classList.replace("unpaid", "paid");
  row.classList.toggle("late", false);
  console.log(row.className);
</script>
Output
fee unpaid highlight
true
fee unpaid selected
fee paid
MethodDescription
add(...names)It is used to add classes (no duplicates).
remove(...names)It is used to remove classes.
toggle(name, force?)It is used to add the class if missing, remove it if present; with force, add when true, remove when false.
contains(name)It is used to check for a class.
replace(old, new)It is used to swap one class for another.

toggle(name, condition) is handy for state: row.classList.toggle("overdue", daysLate > 0).

Inline Styles

element.style sets inline styles directly. CSS property names become camelCase (background-color becomes backgroundColor), and values are strings with units:

style.html
<div id="bar"></div>
<script>
  const bar = document.querySelector("#bar");
  bar.style.width = "75%";
  bar.style.backgroundColor = "seagreen";
  bar.style.setProperty("--progress", "0.75");

  console.log(bar.style.width, bar.style.backgroundColor);
  console.log(bar.getAttribute("style"));
  console.log(getComputedStyle(bar).display);
</script>
Output
75% seagreen
width: 75%; background-color: seagreen; --progress: 0.75;
block

style only reads inline styles. To read the final style after all CSS rules apply, use getComputedStyle(element). Prefer classes for anything that is a "state" (selected, hidden, error); use inline styles for values computed at run time, like a progress bar's width, or set a CSS custom property (--progress) and let the stylesheet use it.

Data Attributes: dataset

data-* attributes store custom data on elements. JavaScript reads and writes them through element.dataset, with names converted to camelCase:

dataset.html
<table><tr id="r1" data-student-id="S-0042" data-amount="120" data-paid="false"><td>Navika</td></tr></table>
<script>
  const row = document.querySelector("#r1");
  console.log(row.dataset.studentId, row.dataset.amount);
  console.log(typeof row.dataset.amount);

  row.dataset.paid = "true";
  row.dataset.paidOn = "2026-01-05";
  console.log(row.getAttribute("data-paid-on"));
</script>
Output
S-0042 120
string
2026-01-05

data-student-id becomes dataset.studentId. Values are always strings: convert with Number(...) before doing math. Data attributes are visible in the page source and editable in DevTools, so never store secrets in them.

In Practice

The Fee Tracker renders a status line for each student safely: names go in with textContent, state is shown with classes, and the amount is stored in a data attribute:

status.html
<ul id="students"></ul>
<script>
  const students = [
    { name: "Navika", balance: 0 },
    { name: "Srihitha <script>", balance: 85 },
  ];

  const list = document.querySelector("#students");
  for (const s of students) {
    const li = document.createElement("li");
    li.textContent = `${s.name}: ${s.balance > 0 ? `$${s.balance} due` : "paid"}`;
    li.classList.toggle("due", s.balance > 0);
    li.dataset.balance = String(s.balance);
    list.append(li);
  }

  console.log(list.children.length);
  console.log(list.children[1].textContent, list.children[1].className);
  console.log(list.querySelectorAll("script").length);
</script>
Output
2
Srihitha <script>: $85 due due
0

The odd name with <script> in it is shown as text, and no script element was created. createElement and append are covered in the next lesson.

Common Mistakes

innerHTML with user data. XSS. Use textContent or createElement.

Reading getAttribute("value") for the current input value. It's the initial value. Use input.value.

Forgetting units in styles. el.style.width = 75 does nothing. Write "75px" or "75%".

Doing math with dataset values. They are strings: "120" + 5 is "1205".

Interview Corner

What is the difference between textContent, innerText and innerHTML?

textContent gets or sets raw text of all descendants and never parses HTML, so it's safe for untrusted text and fast. innerText returns rendered, visible text (respecting CSS) and triggers layout. innerHTML gets the markup or parses a string as HTML on assignment, which enables XSS if the string contains untrusted data.

What is XSS and how do you prevent it in DOM code?

Cross-site scripting: attacker-controlled data executed as code in your page. In DOM code, prevent it by inserting untrusted data only through text APIs (textContent, setAttribute for non-URL attributes, createElement), never through HTML sinks (innerHTML, outerHTML, insertAdjacentHTML, document.write), validating URLs before using them in href or src, and adding defenses such as Content Security Policy and Trusted Types.

Practice

Challenge: Given <p id="msg" class="info"></p>, show the text Payment of $45 failed safely, switch the class from info to error, and store the amount in data-amount. Log the class name and the data attribute.

Show solution
error-msg.html
<p id="msg" class="info"></p>
<script>
  const msg = document.querySelector("#msg");
  msg.textContent = "Payment of $45 failed";
  msg.classList.replace("info", "error");
  msg.dataset.amount = "45";
  console.log(msg.className, msg.dataset.amount);
</script>
Output
error 45

Quick check: Changing the DOM

3 questions
1Which property is safe for inserting text a user typed?
2A user types 85 into an input whose HTML says value="120". What is input.value?
3How do you read data-student-id in JavaScript?

Key Takeaways

TaskCode
Set textel.textContent = "..."
Set an attributeel.setAttribute("aria-label", "...")
Current input valueinput.value
Toggle a state classel.classList.toggle("due", balance > 0)
Inline styleel.style.width = "75%"
Data attributeel.dataset.amount = "120"

Was this tutorial helpful?

Lesson 69 of 139