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 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.
1<!-- HTML part -->2<p id="message">Hello everyone!</p>34<script>5 // Find the paragraph element by its ID6 const paragraphElement = document.getElementById('message');78 // Get the current text content of the paragraph9 const currentText = paragraphElement.textContent;10 console.log('Current text:', currentText); // Output: Current text: Hello everyone!1112 // Set new plain text content for the paragraph13 paragraphElement.textContent = 'Welcome to JavaScript!';14 console.log('New text:', paragraphElement.textContent); // Output: New text: Welcome to JavaScript!1516 // 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.
1<!-- HTML part -->2<div id="content-box">3 <p>This is a <strong>message</strong>.</p>4</div>56<script>7 // Find the div element by its ID8 const contentBox = document.getElementById('content-box');910 // Get the current HTML content of the div11 const currentHTML = contentBox.innerHTML;12 console.log('Current HTML:', currentHTML); // Output: Current HTML: \n <p>This is a <strong>message</strong>.</p>\n13 // Set new HTML content for the div14 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>1617 // The div on the page now shows a new heading and an italic paragraph18</script>
<!-- HTML --><div id="output"></div><script>const output = document.getElementById('output');output.textContent = '<b>Hello World!</b>';// Page shows: <b>Hello World!</b></script>
<!-- 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.
// Display a user's nameconst userName = 'Alice Smith';document.getElementById('name-display').textContent = userName;// Update a scorelet gameScore = 1500;document.getElementById('score-board').textContent = 'Score: ' + gameScore;
// Add a bold error messageconst errorMessage = '<b>Error:</b> Invalid input!';document.getElementById('status-message').innerHTML = errorMessage;// Display a linkconst link = '<a href="#">More Info</a>';document.getElementById('info-area').innerHTML = link;
// Display a user's nameconst userName = 'Alice Smith';document.getElementById('name-display').textContent = userName;// Update a scorelet gameScore = 1500;document.getElementById('score-board').textContent = 'Score: ' + gameScore;
// Add a bold error messageconst errorMessage = '<b>Error:</b> Invalid input!';document.getElementById('status-message').innerHTML = errorMessage;// Display a linkconst 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.
Update a Score Display
If you have a simple score, textContent is perfect. It only needs to show a number or plain text.
1<!-- HTML -->2<span id="player-score">0</span>34<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>
Show a Dynamic Message
To display a message with a bold part, innerHTML is required to make the bold tag work.
1<!-- HTML -->2<p id="status-area"></p>34<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>
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.
1<!-- HTML -->2<ul id="item-list"></ul>34<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 item9 }10 document.getElementById('item-list').innerHTML = listHTML;11 // Item list shows a bulleted list of fruits12</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
| Feature | textContent | innerHTML | When to Use |
|---|---|---|---|
| Content Type | Plain text only | HTML code (text + tags) | Plain text vs. formatted content |
| HTML Parsing | No (treats tags as text) | Yes (renders tags) | If you need tags to be rendered |
| Security Risk | Low (safe for user input) | High (risk of XSS with user input) | If content comes from an untrusted source |
| Performance | Generally faster | Can be slower (browser parses HTML) | For very frequent updates |
| Use Case | Displaying names, scores, simple messages | Creating complex layouts, adding bold/italic text, links | Simple text vs. rich text |
Test Your Knowledge
Test Your Knowledge
Which property should you use to display a user's name (like 'Alice Smith') in a paragraph?
What will be displayed on the page if you run this code? document.getElementById('myDiv').textContent = '<b>Hello</b> World!';
You want to add a clickable link (<a href="...">Click Here</a>) inside an empty <div>. Which property should you use?
Why is it dangerous to use innerHTML with content directly from a user's input?
Quick Reference
Quick Reference
- 1
textContent— gets or sets only the plain text inside an HTML element. - 2
innerHTML— gets or sets the HTML code (including tags) inside an HTML element. - 3Use
textContentfor plain text — it is faster and safer for simple text updates. - 4Use
innerHTMLfor HTML — use it when you need to add bold, italic, links, or other HTML structures. - 5Security Warning — never use
innerHTMLwith uncleaned user input due to XSS risks. - 6
textContenttreats tags as text — if you settextContent = '<b>Hi</b>', the page will literally show<b>Hi</b>. - 7
innerHTMLrenders tags — if you setinnerHTML = '<b>Hi</b>', the page will show Hi. - 8Performance —
textContentis 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.