← Back to all tutorials

Changing Text & HTML Content

Modify element content with textContent, innerText, and innerHTML — understand the differences and when to use each.

Changing Text & HTML Content

Once you have selected an element, you can read and change its content. JavaScript provides three properties for this: textContent, innerText, and innerHTML.

textContent

var title = document.querySelector('h1');

// Read
console.log(title.textContent); // "Hello World"

// Write
title.textContent = 'New Title';
title.textContent = '<em>bold</em>'; // Displays as literal text, not HTML

textContent returns all text inside an element, including text in hidden elements. It treats everything as plain text — HTML tags are displayed as literal text, not rendered.

innerText

var content = document.querySelector('.content');
console.log(content.innerText); // Only visible text

innerText returns only the visible text. It respects CSS — if text is hidden with display: none, innerText skips it, while textContent includes it.

innerHTML

var content = document.querySelector('.content');

// Read — includes HTML tags
console.log(content.innerHTML); // "<p>Hello <strong>World</strong></p>"

// Write — HTML is parsed and rendered
content.innerHTML = '<h2>New Heading</h2><p>New paragraph</p>';

// Add to existing content
content.innerHTML += '<p>Another paragraph</p>';

innerHTML reads and writes the full HTML inside an element. HTML tags are parsed and rendered. Be careful with user input — using innerHTML with untrusted data can cause XSS vulnerabilities.

Comparison

PropertyReturnsRenders HTML?Hidden Text?
textContentAll text (plain)No — shows tags as textYes — includes hidden text
innerTextVisible text onlyNo — shows tags as textNo — respects CSS
innerHTMLHTML stringYes — parses and rendersYes — includes hidden markup

Changing Multiple Elements

var items = document.querySelectorAll('.item');
items.forEach(function(item) {
    item.textContent = 'Updated!';
});

Key Takeaways

  • textContent is fastest and safest — sets plain text, ignores HTML
  • innerText returns only visible text — respects CSS display rules
  • innerHTML reads and writes HTML — use with caution (XSS risk)
  • Use textContent for plain text; innerHTML only when you need to insert HTML