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 riskinnerHTML — 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 HTMLAll lessons in this course
- querySelector and querySelectorAll
- addEventListener and Event Object
- Changing Content: textContent innerHTML classList
- Creating and Appending Elements