Changing Content and Styles
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 = textsets plain text. Safe for any input. Use it by default.element.innerHTML = htmlparses 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 throughelement.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:
<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>Loading...
Navika paid $120.
<b>bold?</b>
0Explanation: setting textContent to "<b>bold?</b>" shows those characters literally on the page; no <b> element is created. The browser stores them escaped (< is <), which is why innerHTML reads back the escaped form and the paragraph has no child elements.
| Property | Gets | Sets |
|---|---|---|
textContent | All text, including hidden elements | Plain text (safe) |
innerText | Only text that is visible, as styled | Plain text (safe), but triggers a layout calculation |
innerHTML | The HTML markup inside | Parses the string as HTML (dangerous with user input) |
outerHTML | The element's own markup too | Replaces 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":
<p id="welcome"></p>
<script>
const nameFromForm = '<img src="x" onerror="console.log(\'Attacker code ran!\')">';
document.querySelector("#welcome").innerHTML = `Welcome, ${nameFromForm}`;
</script>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:
<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>0The 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:
<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>/fees
true
85 120
true page
falseExplanation:
getAttribute("href")returns exactly what the HTML says; thehrefproperty returns the full resolved URL (here the page's own address plus/fees, so the example checks only the end).- For inputs, the
valueproperty is the current value; thevalueattribute is only the starting value. After typing (or setting the property), they differ. setAttribute,hasAttributeandremoveAttributework 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:
<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>fee unpaid highlight
true
fee unpaid selected
fee paid| Method | Description |
|---|---|
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:
<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>75% seagreen
width: 75%; background-color: seagreen; --progress: 0.75;
blockstyle 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:
<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>S-0042 120
string
2026-01-05data-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:
<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>2
Srihitha <script>: $85 due due
0The 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
<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>error 45Key Takeaways
| Task | Code |
|---|---|
| Set text | el.textContent = "..." |
| Set an attribute | el.setAttribute("aria-label", "...") |
| Current input value | input.value |
| Toggle a state class | el.classList.toggle("due", balance > 0) |
| Inline style | el.style.width = "75%" |
| Data attribute | el.dataset.amount = "120" |
Was this tutorial helpful?