Episode 36 of 46
Changing HTML Page Content
Learn how to dynamically change text and HTML content on a web page.
JavaScript can dynamically change what appears on a web page by modifying the content of elements.
textContent
Gets or sets the text only (strips all HTML tags):
let heading = document.querySelector("h1");
// Get text
console.log(heading.textContent);
// Set text
heading.textContent = "New Heading";
// HTML tags are displayed as plain text
heading.textContent = "<em>Hello</em>";
// Shows: <em>Hello</em> (literally)
innerHTML
Gets or sets the HTML content (parses HTML tags):
let container = document.querySelector(".content");
// Get HTML
console.log(container.innerHTML);
// Set HTML (tags are rendered)
container.innerHTML = "<h2>Hello</h2><p>World</p>";
// Add to existing content
container.innerHTML += "<p>Another paragraph</p>";
innerText vs textContent
// innerText — aware of styling (hidden elements ignored)
// textContent — returns ALL text regardless of visibility
// If an element has display: none children:
el.textContent; // Includes hidden text
el.innerText; // Excludes hidden text
Practical Example
// Dynamic greeting
let nameEl = document.querySelector("#user-name");
let greetingEl = document.querySelector("#greeting");
let hour = new Date().getHours();
let greeting;
if (hour < 12) greeting = "Good morning";
else if (hour < 18) greeting = "Good afternoon";
else greeting = "Good evening";
greetingEl.textContent = `${greeting}, welcome to our site!`;
Security Warning
Never use innerHTML with user input — it can lead to XSS attacks. Use textContent for user-provided data.