0Pricing
Frontend Academy · Lesson

Changing Content: textContent innerHTML classList

Read and update element text content, inject HTML, and toggle, add, and remove CSS classes programmatically.

Reading and Writing textContent

element.textContent gets or sets the plain text content of an element, including all descendants. It's safe — it never parses HTML, so setting it with user input doesn't create XSS vulnerabilities.

const heading = document.querySelector('h1');
console.log(heading.textContent); // read
heading.textContent = 'New Title'; // write — replaces all children

// Safe with user input:
element.textContent = userInput; // no XSS risk

innerHTML — Use With Caution

element.innerHTML gets or sets the HTML markup inside an element. Convenient, but dangerous with user input — it parses HTML and can execute scripts (XSS). Never set innerHTML with unsanitised user data.

card.innerHTML = '<strong>Loading...</strong>'; // safe: hardcoded string

// DANGER — never do this:
element.innerHTML = userInput; // XSS vulnerability

// Safe alternative:
const div = document.createElement('div');
div.textContent = userInput;   // won't parse as HTML

All lessons in this course

  1. querySelector and querySelectorAll
  2. addEventListener and Event Object
  3. Changing Content: textContent innerHTML classList
  4. Creating and Appending Elements
← Back to Frontend Academy