Changing Content & Styles
Once you have selected an element, you can change almost anything about it: its text, its HTML, its attributes, its classes and its styles. You can also build brand-new elements and add them to the page. These few tools are behind every live counter, pop-up message and shopping cart on the web.
Changing text: textContent
textContent reads or replaces all the text inside an element. Whatever you assign is treated as plain text, even if it looks like HTML.
<h1 id="title">Today's prices</h1> <p id="banner"></p>
const title = document.querySelector("#title");
console.log(title.textContent);
title.textContent = "Bei za leo";
console.log(title.textContent);
const banner = document.querySelector("#banner");
banner.textContent = "<strong>Sold out</strong>";
console.log(banner.children.length);
The banner now displays the characters <strong>Sold out</strong> literally; no strong element was created, so it has zero children. You may also see innerText, which is similar but only returns text that is visible on screen (it respects CSS). Prefer textContent: it is faster and predictable.
Changing HTML: innerHTML
innerHTML reads or replaces the HTML inside an element. The browser parses the string and builds real elements.
banner.innerHTML = "<strong>Sold out</strong> today"; console.log(banner.children.length); console.log(banner.textContent);
Never put text typed by a user (or loaded from another site) into innerHTML. If someone types <img src=x onerror="alert('hacked')"> as their "name", the browser creates that element and runs its code. This attack is called cross-site scripting (XSS). Use textContent for anything a user typed, and keep innerHTML for HTML you wrote yourself.
Attributes and properties
Most HTML attributes appear as properties on the element object, so you can read and set them directly: img.src, link.href, input.value, input.disabled, checkbox.checked. For any attribute you can also use getAttribute, setAttribute and removeAttribute.
Custom data belongs in data-* attributes, which you read through dataset. Dashed names become camelCase, and values are always strings.
<button id="buy" data-product-id="42" data-price="150">Buy</button>
const buy = document.querySelector("#buy");
console.log(buy.dataset.productId);
console.log(Number(buy.dataset.price) * 2);
buy.disabled = true;
buy.setAttribute("title", "Out of stock");
console.log(buy.getAttribute("title"));
Changing styles: classList first
You can set inline styles with element.style. CSS property names become camelCase, so background-color is style.backgroundColor:
title.style.color = "darkgreen"; title.style.backgroundColor = "#fff8e1";
A cleaner habit is to describe the look in your CSS file and use JavaScript only to add or remove classes. That keeps styling in one place and makes changes easy. classList has everything you need:
<div class="card hidden">M-Pesa balance</div>
const card = document.querySelector(".card");
card.classList.add("active");
card.classList.remove("hidden");
card.classList.toggle("dark"); // adds it, because it was missing
console.log(card.classList.contains("dark"));
console.log(card.className);
card.classList.toggle("dark", false); // second argument forces off
console.log(card.className);
Creating, adding and removing elements
To add new content safely, create an element, fill it, then attach it to the page:
document.createElement("li")makes an element that isn't on the page yet.- Set its
textContent, classes and attributes. - Attach it with
parent.append(child)(at the end),parent.prepend(child)(at the start), orelement.before()/element.after().
Here we turn an array into a list. The ul starts empty:
const fruits = ["Mango", "Pawpaw", "Passion"];
const list = document.querySelector("#fruits");
for (const fruit of fruits) {
const li = document.createElement("li");
li.textContent = fruit;
list.append(li);
}
console.log(list.children.length);
list.firstElementChild.remove(); // delete an element
console.log(list.children.length, list.firstElementChild.textContent);
To empty an element completely, call list.replaceChildren() with no arguments. If you have HTML you wrote yourself, element.insertAdjacentHTML("beforeend", html) adds it without destroying what is already there.
Building a list with list.innerHTML += "<li>...</li>" inside a loop. Each += throws away every existing child and re-parses the whole list, which is slow and removes any event listeners attached to those children. Use createElement and append, or build one string and assign it once.
Try it: a shopping list card
Add and remove items, and toggle dark mode with classList. The counter uses a template literal. Try adding a button that clears the list with replaceChildren().
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
.card { padding: 12px; border: 2px solid #1f2d42; border-radius: 8px; max-width: 320px; }
.dark { background: #1f2d42; color: white; }
</style>
</head>
<body>
<div class="card">
<h2>Shopping list</h2>
<ul id="items"></ul>
<p id="count">0 items</p>
<button id="add">Add item</button>
<button id="remove">Remove last</button>
<button id="theme">Toggle dark mode</button>
</div>
<script>
const ideas = ["Unga", "Sukari", "Maziwa", "Mkate", "Chai"];
const list = document.querySelector("#items");
const count = document.querySelector("#count");
const card = document.querySelector(".card");
function updateCount() {
count.textContent = `${list.children.length} items`;
}
document.querySelector("#add").addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = ideas[list.children.length % ideas.length];
list.append(li);
updateCount();
});
document.querySelector("#remove").addEventListener("click", () => {
list.lastElementChild?.remove();
updateCount();
});
document.querySelector("#theme").addEventListener("click", () => {
card.classList.toggle("dark");
});
</script>
</body>
</html>
Key points
textContentsets plain text;innerHTMLparses HTML, so never feed it user input.- Attributes are available as properties; custom data lives in
data-*anddataset(always strings). - Prefer
classList.add/remove/toggleover inlinestylechanges. - Create elements with
createElement, attach withappend/prepend, delete withremove().
Tip: use the ← and → keys to move between pages.
