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
| Property | Returns | Renders HTML? | Hidden Text? |
|---|---|---|---|
textContent | All text (plain) | No — shows tags as text | Yes — includes hidden text |
innerText | Visible text only | No — shows tags as text | No — respects CSS |
innerHTML | HTML string | Yes — parses and renders | Yes — includes hidden markup |
Changing Multiple Elements
var items = document.querySelectorAll('.item');
items.forEach(function(item) {
item.textContent = 'Updated!';
});
Key Takeaways
textContentis fastest and safest — sets plain text, ignores HTMLinnerTextreturns only visible text — respects CSS display rulesinnerHTMLreads and writes HTML — use with caution (XSS risk)- Use
textContentfor plain text;innerHTMLonly when you need to insert HTML