Lesson 10 of 28
In progress
Changing content, classes and styles
Update text safely, build elements, toggle classes for state, and keep styling decisions in CSS where they belong.
Once you can find an element, the next question is how to change it without breaking the page or opening a security hole. The rule is simple: text goes in as text, structure goes in as elements, and appearance goes in CSS.
What you will learn
- Set text and attributes safely.
- Create and insert elements instead of concatenating HTML.
- Toggle state with classes and custom properties.
Text
Editable. Runs in your browser.
<script>
const message = document.querySelector("#message");
message.textContent = "New message";
console.log(message.textContent);
</script>
Press Run to see the output.
textContent reads and writes the text of an element and all its descendants. It cannot interpret markup, which makes it the safe default for anything a user typed.
innerText is similar but depends on rendering: it ignores hidden text and forces layout calculations. Use textContent unless you specifically need the visible text.
HTML, carefully
innerHTML parses a string as HTML. That is useful for trusted templates and dangerous for user input, because a script tag or an event handler in the string can execute.
Editable. Runs in your browser.
<script>
const box = document.querySelector("#box");
box.innerHTML = "<strong>Trusted</strong> markup";
const userText = "<img src=x onerror=alert(1)>";
box.textContent = userText;
console.log(box.textContent);
</script>
Press Run to see the output.
The first assignment renders bold text. The second shows the literal characters, which is what you want for a comment or a name. If you ever find yourself building HTML with + and a variable, stop and use elements instead.
Creating elements
Editable. Runs in your browser.
<script>
const list = document.querySelector("#tasks");
const items = ["Read", "Practise", "Build"];
items.forEach((label) => {
const li = document.createElement("li");
li.textContent = label;
li.dataset.label = label.toLowerCase();
list.append(li);
});
console.log(list.children.length);
</script>
Press Run to see the output.
createElement builds a node, and append inserts it. append accepts several nodes and strings; appendChild takes one node. prepend inserts at the start, and insertBefore places a node relative to another.
Building a list this way is safe and lets you attach listeners to each item. For repeated complex markup, a <template> element plus cloneNode(true) is cleaner than creating ten nested elements by hand.
A template element is the clean way to repeat complex markup. Its contents are inert until cloned, so no scripts run and no images load early.
Editable. Runs in your browser.
<script>
const template = document.querySelector("#row");
const rows = document.querySelector("#rows");
["One", "Two"].forEach((label) => {
const clone = template.content.cloneNode(true);
clone.querySelector("span").textContent = label;
rows.append(clone);
});
</script>
Press Run to see the output.
The clone is a document fragment, so appending it inserts its children. Text still goes in through textContent, which keeps the safety rule intact even when the structure comes from HTML.
Classes for state
Editable. Runs in your browser.
<div class="card" id="card">Toggle me</div>
<button id="toggle" type="button">Toggle active</button>
<script>
const card = document.querySelector("#card");
const toggle = document.querySelector("#toggle");
toggle.addEventListener("click", () => {
card.classList.toggle("is-active");
console.log(card.classList.contains("is-active"));
});
</script>
Press Run to see the output.
classList has add, remove, toggle and contains. The is- prefix is a convention that marks a state class, which makes it obvious in the HTML that the class is managed by script rather than by layout.
Do not set element.style for anything that belongs in a stylesheet. Inline styles are hard to override, they bypass media queries and dark mode, and they scatter design decisions through JavaScript.
Custom properties from script
The one styling job that belongs in JavaScript is a value only the script knows, such as a progress percentage.
Editable. Runs in your browser.
<script>
const fill = document.querySelector("#fill");
const percent = 64;
fill.style.setProperty("–progress", `${percent}%`);
fill.style.width = "var(–progress)";
console.log(getComputedStyle(fill).width);
</script>
Press Run to see the output.
Setting a custom property keeps the value inspectable and lets CSS decide how to use it. Direct style.width is fine for a one-off; the token approach scales better when several rules depend on the same number.
Attributes
Editable. Runs in your browser.
<script>
const photo = document.querySelector("#photo");
photo.setAttribute("alt", "A small dog wrapped in a blanket");
photo.removeAttribute("width");
console.log(photo.getAttribute("alt"));
</script>
Press Run to see the output.
Use setAttribute for attributes such as aria-label, href and disabled. For booleans, the property form is clearer: button.disabled = true.
When changing href from user data, validate the scheme first. A javascript: URL is executable, and setting it from untrusted input is a script injection.
Building markup with innerHTML and string concatenation turns any user-provided name into potential HTML. A comment containing <img onerror=...> becomes executable. Create nodes and set textContent; it costs three lines and removes the class of bug entirely.
Build a status badge: given a state of "open", "closed" or "pending", set the badge’s text and toggle a matching class. Use the state as a data-state attribute and style it with CSS attribute selectors.
Show solution
Editable. Runs in your browser.
<p class="badge" id="badge">Status</p>
<script>
const badge = document.querySelector("#badge");
function setState(state) {
badge.dataset.state = state;
badge.textContent = state.charAt(0).toUpperCase() + state.slice(1);
}
setState("open");
console.log(badge.outerHTML);
</script>
Press Run to see the output.
The state lives in one attribute, CSS decides the colours, and the text is derived from the same value. Adding a fourth state is a CSS rule plus a call, not another branch in the script.
Recap
textContentis the safe way to write text;innerHTMLis for trusted markup only.- Create elements and append them instead of concatenating HTML strings.
- State belongs in classes or data attributes, with CSS owning the appearance.
Next, you will respond to clicks, typing and other events.
Does innerHTML remove event listeners?
Why does my style not apply?
Progress is saved in this browser only. No account, no email.