Topic 77 of 87
Changing HTML & Text
Overview
Once you have selected an element, you can modify its internal content. There are three primary properties used for this: innerText, textContent, and innerHTML.
While they seem similar, they behave differently regarding how they handle hidden CSS elements and raw HTML parsing.
Syntax
innerText vs textContent
javascript
const title = document.querySelector('.title');
// Changes the visible text
title.innerText = "Welcome to the App!";
// textContent is faster, but gets ALL text (even if hidden by CSS)
console.log(title.textContent);DANGER: innerHTML
javascript
const container = document.querySelector('.container');
// innerHTML parses strings into actual DOM nodes!
container.innerHTML = "<h2>Rendered as a real heading!</h2>";
// DANGER: Never do this with user input!
// container.innerHTML = userInput; // Cross-Site Scripting (XSS) Attack!Common Pitfalls
- Using
innerHTMLwith unsanitized user input. If a user enters<script>stealCookies()</script>into a comment box, and you useinnerHTMLto display it on the page, the browser will literally execute their malicious script! This is called an XSS vulnerability. Always useinnerTextfor user-generated text.
Interview Questions
Q:
What is the security risk of using
innerHTML?A:
Using innerHTML exposes your application to Cross-Site Scripting (XSS) attacks. If malicious user input containing <script> tags is injected via innerHTML, the browser will execute that code, potentially stealing tokens or session data.
Real-World Example
Updating a notification badge number in a navigation bar.
example
javascript
const badge = document.querySelector('.cart-count');
badge.innerText = cartItems.length.toString();Check Your Knowledge
Test your understanding of Changing HTML & Text with these quick questions.