Lesson 3: Changing Content and Styles

Learning Objectives

By the end of this lesson, learners will be able to:

  • Change the text and HTML content of DOM elements
  • Modify CSS styles of elements using JavaScript
  • Add, remove, and toggle CSS classes dynamically
  • Understand the difference between textContent, innerText, and innerHTML

Why Change Content and Styles?

Once you’ve selected an element from the DOM, you can update what it shows or how it looks — all without reloading the page.

This is how websites:

  • Update content after a button click
  • Show or hide sections
  • Change colors, sizes, and layouts interactively

With JavaScript, your webpage becomes alive and responsive to users.


1. Changing Text Content

Use .textContent to change the text inside an element:

<p id="status">Loading...</p>
let status = document.getElementById("status");
status.textContent = "Finished!";

Use .textContent when:

  • You only want to update the text (not HTML)
  • You don’t want to interpret HTML tags

2. Using .innerHTML (When You Need HTML)

If you want to insert HTML elements into your content (like bold text or links), use .innerHTML.

<p id="info">Old info</p>
document.getElementById("info").innerHTML = "<strong>Updated info</strong>";

Be careful when inserting user input with .innerHTML — it can expose your site to XSS attacks.


.innerText vs .textContent

PropertyReads hidden elements?Reads only visible text?Includes spacing?
.textContent✅ Yes❌ No✅ Yes
.innerText❌ No✅ Yes✅ Yes

Use .textContent in most cases for consistency and performance.


3. Changing CSS Styles with JavaScript

Every DOM element has a .style object where you can directly modify CSS properties.

Example:

<p id="message">Hello!</p>
let msg = document.getElementById("message");
msg.style.color = "blue";
msg.style.fontSize = "20px";
msg.style.backgroundColor = "#f0f0f0";

Use camelCase for multi-word CSS properties:

  • background-colorbackgroundColor
  • font-sizefontSize

4. Adding and Removing CSS Classes

Instead of changing styles directly, you can apply predefined CSS classes using .classList.

Example:

<p id="alert" class="hidden">This is an alert</p>
let alertBox = document.getElementById("alert");

alertBox.classList.remove("hidden");  // Show it
alertBox.classList.add("visible");    // Apply a new style

Toggle a class on/off:

alertBox.classList.toggle("active");

This is cleaner and more scalable than editing .style directly — keep your CSS rules in a stylesheet.


Quick Summary: What Can You Change?

FeatureJavaScript PropertyExample
Text content.textContentelement.textContent = "Hi!"
HTML content.innerHTMLelement.innerHTML = "<b>Hi</b>"
Style.style.propertyNameelement.style.color = "red"
CSS classes.classList.add/removeelement.classList.add("dark")