Back to course

Changing Text Content: textContent vs. innerHTML

JavaScript: The Complete '0 to Hero' Beginner Course

81. Changing Text Content

Once an element is selected, we can modify its content using two main properties.

1. textContent (Text Only)

Sets or returns the textual content of the element and all its descendants. It automatically escapes any HTML tags, treating them as plain text.

javascript const output = document.getElementById('output');

output.textContent = 'This is new text.';

// Using textContent is safer, as HTML is rendered as text: output.textContent = '

Danger!

'; // The browser will display the literal string '

Danger!

'

2. innerHTML (Text and HTML Markup)

Sets or returns the HTML content (markup) inside an element. This is necessary if you need to dynamically inject new elements.

javascript const list = document.querySelector('.list');

// Injecting an

  • element list.innerHTML = '
  • First Item
  • Second Item
  • ';

    // Caution: Security Risk (XSS) list.innerHTML = someUserInput; // If user input contains malicious scripts, they will execute.

    Rule of Thumb: Use textContent whenever you are only dealing with text. Use innerHTML only when you must inject structural HTML, and only with trusted data.