javascript

InnerHTML and TextContent

Learn how innerHTML and textContent in JavaScript help you get and set content inside HTML elements. Discover their key differences, security implications, and best use cases.

10 min read 8 sections Tutorial
Share

In JavaScript, you often need to change what users see on a web page. Two important tools for this are `innerHTML` and `textContent`. They let you read or write information inside any HTML element, like a paragraph or a heading. Understanding when to use each one is key to building safe and dynamic web pages. This tutorial will show you exactly how they work and when to pick one over the other.

InnerHTML and TextContent

InnerHTML and TextContent

Web pages are made of HTML elements. Think of these as boxes on your page. Sometimes you want to see what is inside a box, or put new things inside it.

In JavaScript, innerHTML and textContent are like special tools for these boxes. They help you get the existing content from an HTML element or put new content into it. They both work on text, but innerHTML can also handle full HTML code, while textContent only deals with plain text.

What are They?

innerHTML gets or sets the HTML content of an element, including any tags. textContent gets or sets only the plain text content, ignoring any HTML tags inside.

Plain Text Only

textContent is best for working with just text. It does not care about bold tags or links. It gives you raw words.

HTML Content

innerHTML can read and write full HTML code. This means you can add <p> tags, <strong> tags, or <a> links.

Security First

textContent is safer because it cannot run harmful code. innerHTML needs careful use to avoid security problems.

Dynamic Updates

Both allow you to change parts of your web page after it loads. This makes your pages interactive and alive.

Getting Started with TextContent

Getting Started

Getting Started with TextContent

Let's start with textContent. It is the simpler and often safer choice. Imagine you have a paragraph on your web page and you want to change its words. textContent lets you do exactly that.

First, you need to find the HTML element you want to change. You can do this using document.getElementById() if your element has an id. Then, you use .textContent to get or set its text.

JS · Browser
1<!-- HTML part -->
2<p id="message">Hello everyone!</p>
3
4<script>
5 // Find the paragraph element by its ID
6 const paragraphElement = document.getElementById('message');
7
8 // Get the current text content of the paragraph
9 const currentText = paragraphElement.textContent;
10 console.log('Current text:', currentText); // Output: Current text: Hello everyone!
11
12 // Set new plain text content for the paragraph
13 paragraphElement.textContent = 'Welcome to JavaScript!';
14 console.log('New text:', paragraphElement.textContent); // Output: New text: Welcome to JavaScript!
15
16 // The paragraph on the page now shows "Welcome to JavaScript!"
17</script>

textContent ignores HTML tags

If you try to set textContent with HTML tags, it will treat the tags as plain text. For example, element.textContent = '<b>Hello</b>' will display <b>Hello</b> on the page, not a bold "Hello".

Understanding InnerHTML

Understanding InnerHTML

Now let's look at innerHTML. This property is more powerful because it understands HTML code. If you want to add bold text, a link, or even a new paragraph inside an existing element, innerHTML is the tool you need.

When you get innerHTML, it gives you all the HTML code inside the element, including any tags. When you set innerHTML, the browser reads the new HTML code and draws it on the page.

JS · Browser
1<!-- HTML part -->
2<div id="content-box">
3 <p>This is a <strong>message</strong>.</p>
4</div>
5
6<script>
7 // Find the div element by its ID
8 const contentBox = document.getElementById('content-box');
9
10 // Get the current HTML content of the div
11 const currentHTML = contentBox.innerHTML;
12 console.log('Current HTML:', currentHTML); // Output: Current HTML: \n <p>This is a <strong>message</strong>.</p>\n
13 // Set new HTML content for the div
14 contentBox.innerHTML = '<h2>New Heading</h2><p>This text is <em>important</em>.</p>';
15 console.log('New HTML:', contentBox.innerHTML); // Output: New HTML: <h2>New Heading</h2><p>This text is <em>important</em>.</p>
16
17 // The div on the page now shows a new heading and an italic paragraph
18</script>
✗ BadWrong — textContent for HTML
<!-- HTML -->
<div id="output"></div>
<script>
const output = document.getElementById('output');
output.textContent = '<b>Hello World!</b>';
// Page shows: <b>Hello World!</b>
</script>
✓ GoodCorrect — innerHTML for HTML
<!-- HTML -->
<div id="output"></div>
<script>
const output = document.getElementById('output');
output.innerHTML = '<b>Hello World!</b>';
// Page shows: Hello World! (bold)
</script>

Choosing Between TextContent and InnerHTML

Choosing Between TextContent and InnerHTML

Deciding which one to use is important. The main difference is simple: do you need to work with plain words, or do you need to work with full HTML code? Always choose the simplest and safest tool for the job.

textContent is usually faster and always safer. Use it when you only need to display text that does not contain any special HTML formatting. innerHTML is powerful but comes with security risks if you are not careful.

Use textContent for plain text
// Display a user's name
const userName = 'Alice Smith';
document.getElementById('name-display').textContent = userName;
// Update a score
let gameScore = 1500;
document.getElementById('score-board').textContent = 'Score: ' + gameScore;
VS
Use innerHTML for HTML structure
// Add a bold error message
const errorMessage = '<b>Error:</b> Invalid input!';
document.getElementById('status-message').innerHTML = errorMessage;
// Display a link
const link = '<a href="#">More Info</a>';
document.getElementById('info-area').innerHTML = link;

Security with innerHTML

Never use innerHTML to put content directly from a user (like from a text box) onto your page. A bad user could enter harmful HTML code that steals information or breaks your website. This is called a Cross-Site Scripting (XSS) attack. Always use textContent for user-provided text.

Practical Use Cases

Practical Use Cases

Let's see how textContent and innerHTML are used in common web development tasks. You will often use them to update parts of your page without reloading it, making your website feel fast and modern.

Imagine you are building a simple game or a dashboard. You might need to update a score, a timer, or a list of items. These are perfect jobs for these properties.

1

Update a Score Display

If you have a simple score, textContent is perfect. It only needs to show a number or plain text.

JS · Browser
1<!-- HTML -->
2<span id="player-score">0</span>
3
4<script>
5 let score = 0;
6 function updateScore(points) {
7 score += points;
8 document.getElementById('player-score').textContent = score;
9 }
10 updateScore(10);
11 // Player score shows '10'
12</script>
2

Show a Dynamic Message

To display a message with a bold part, innerHTML is required to make the bold tag work.

JS · Browser
1<!-- HTML -->
2<p id="status-area"></p>
3
4<script>
5 function showStatus(message) {
6 document.getElementById('status-area').innerHTML = '<b>Status:</b> ' + message;
7 }
8 showStatus('Game started!');
9 // Status area shows: Status: Game started! (with 'Status:' bold)
10</script>
3

Build a List of Items

If you need to add multiple HTML elements, you can build a string of HTML and then set it with innerHTML.

JS · Browser
1<!-- HTML -->
2<ul id="item-list"></ul>
3
4<script>
5 const items = ['Apple', 'Banana', 'Cherry'];
6 let listHTML = '';
7 for (const item of items) {
8 listHTML += '<li>' + item + '</li>'; // Build HTML for each list item
9 }
10 document.getElementById('item-list').innerHTML = listHTML;
11 // Item list shows a bulleted list of fruits
12</script>

Input from Users and innerHTML

Imagine a comment box where users type. If you use innerHTML to display their comments, and a user types <script>alert('You are hacked!')</script>, that script will run on your page! This is dangerous. Always use textContent when displaying any text that came from a user.

Comparison Table

Comparison Table

FeaturetextContentinnerHTMLWhen to Use
Content TypePlain text onlyHTML code (text + tags)Plain text vs. formatted content
HTML ParsingNo (treats tags as text)Yes (renders tags)If you need tags to be rendered
Security RiskLow (safe for user input)High (risk of XSS with user input)If content comes from an untrusted source
PerformanceGenerally fasterCan be slower (browser parses HTML)For very frequent updates
Use CaseDisplaying names, scores, simple messagesCreating complex layouts, adding bold/italic text, linksSimple text vs. rich text

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which property should you use to display a user's name (like 'Alice Smith') in a paragraph?

Quick Check

What will be displayed on the page if you run this code? document.getElementById('myDiv').textContent = '<b>Hello</b> World!';

Quick Check

You want to add a clickable link (<a href="...">Click Here</a>) inside an empty <div>. Which property should you use?

Quick Check

Why is it dangerous to use innerHTML with content directly from a user's input?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1textContent — gets or sets only the plain text inside an HTML element.
  • 2innerHTML — gets or sets the HTML code (including tags) inside an HTML element.
  • 3Use textContent for plain text — it is faster and safer for simple text updates.
  • 4Use innerHTML for HTML — use it when you need to add bold, italic, links, or other HTML structures.
  • 5Security Warning — never use innerHTML with uncleaned user input due to XSS risks.
  • 6textContent treats tags as text — if you set textContent = '<b>Hi</b>', the page will literally show <b>Hi</b>.
  • 7innerHTML renders tags — if you set innerHTML = '<b>Hi</b>', the page will show Hi.
  • 8PerformancetextContent is generally faster because the browser does not need to parse HTML.
  • 9Replacement — both properties replace all existing content inside the element when you set them.
  • 10Finding Elements — always get a reference to the HTML element first, typically with document.getElementById().

DOM Manipulation

Learn more ways to add, remove, and change HTML elements in JavaScript, beyond just text content.

Event Listeners

Understand how to make your page react when users click buttons or type into fields.

Web Security Basics

Dive deeper into common web security threats like XSS and how to protect your applications.

JavaScript Functions

Master writing reusable blocks of code to make your dynamic page updates organized and efficient.

You now understand InnerHTML and TextContent!

You have learned the essential differences between innerHTML and textContent, when to use each, and how to keep your web pages secure. These are fundamental tools for making interactive websites with JavaScript!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning