Do you really know the exact differences between innerHTML Vs innerText Vs textContent??

Mohith Gupta
6 min readDec 30, 2023

--

Photo by Jackson Sophat on Unsplash

innerHTML, innerText, and textContent are properties used to manipulate the content of HTML elements in JavaScript, but they differ in their behaviour of getting and setting content. Let’s get right into it!

I will be using the following example to explain the behaviour going forward, so please take a thorough look at this:

image of example code from my editor

innerHTML:

  • innerHTML sets or gets the HTML content inside an element, allowing you to insert HTML markup.
  • It retrieves HTML content, including tags, attributes, and text.

Getting content with innerHTML

// Reading content with innerHTML
const h1Element = document.querySelector('h1')
console.log(h1Element.innerHTML)
image of an example code from my editor

The innerHTML property returns the full content including all the HTML tags inside the h1 element and their text content.

Setting content with innerHTML

You can just assign some content to the innerHTML property.

h1Element.innerHTML = `
<p> Index </p>
<p style="display: none;"> About </p>
<p> Team </p>
`
image of an example code from my editor

The JavaScript code passes a string of an HTML list as the value for innerHTML. The innerHTML property recognizes the HTML tags and formats the content accordingly.

Unlike innerHTML, both innerText and textContent will ignore the HTML tags and render everything as a string.

Important Note: Be cautious when using innerHTML as it can execute scripts and potentially expose your application to security risks if the content is not sanitized. More on that at the end. Make sure you read that part.

innerText:

  • innerText sets or gets the visible text content of an element, considering styling and visibility (Ex: display: none elements won't have innerText values)
  • It’s slower than textContent and doesn't maintain whitespace or formatting information.

Getting content with innerText

// Reading content with innerText
const h1Element = document.querySelector('h1')
console.log(h1Element.innerText)
image of an example code from my editor

The innerText property returns the content as rendered on the screen. It ignores all the HTML tags. It also ignores the hidden element with the display property set to none.

Setting content with innerText

We assign some content to the property itself.

h1Element.innerText = `
<p> Index </p>
<p style="display: none;"> About </p>
<p> Team </p>
`
image of an example code from my editor

Note how innerText ignores the HTML tags but still recognises formatting like line-breaks and whitespaces.

textContent:

  • textContent sets or gets the text content of an element, including all nodes and their textual representation (preserving whitespace and formatting)
  • It’s faster than innerText and doesn't consider styling or rendering.

Getting content with textContent

// Reading content with textContent
const h1Element= document.querySelector('h1')
console.log(h1Element.textContent)
image of an example code from my editor

The textContent property returns the content as it is in the HTML markup. It ignores the HTML tags as well as the styles, so it returns the "About Me" text even though it's hidden.

Setting content with textContent

When setting or updating content, the textContent property will ignore HTML markup and it will also ignore things like line breaks and whitespaces.

h1Element.textContent = `
<p> Index </p>
<p style="display: none;"> About </p>
<p> Team </p>
`
image of an example code from my editor

When you want the raw text and aren't concerned with the formatting of the text, textContent is a suitable choice.

Security Concerns When Using innerHTML

Because innerHTML processes and interprets HTML tags, it’s advisable to use this only when inserting content from trusted sources. Or when you have properly sanitised and validated the provided content.

The browser will run any JavaScript code you put in the HTML script tag. And it can open doors to Cross-Site Scripting (XSS) where attackers can inject and run malicious scripts in the context of your web page.

Let’s see an example:

<div id="postSection"></div>

Assume you are using the div above as a container for the user’s post in your app. And you are using innerHTML to add new posts without any validation or sanitizing the post.

Here is a fundamental example of how a user can inject and run a malicious script:

    const postSection = document.getElementById('postSection')
let userInput = `...form Input of Post details from the app...`;
postSection.innerHTML = userPost;

We are receiving this userInput value from the text editor form in your app where the user can type anything. So, we are assuming he types some javascript malicious code and we are setting the content without sanitizing it!

let userInput = `<img src="malicious-code.jpg" onerror="alert('Malicious Code Executing!')"> This is my Input!`;

The user deliberately gives an invalid value for the src attribute of the image. This will trigger the onerror event which runs an alert with the string "Malicious Code Executing!" which is not expected.

image of an example code from my editor

You can imagine how an attacker can use this to inject harmful JavaScript code, run queries on DB if possible, potentially steal sensitive user information, or perform other malicious actions.

To prevent XSS attacks when using innerHTML, it's crucial to properly sanitize user input or escape special characters to ensure they are treated as plain text rather than executable code:

const userInput = '<img src="invalid-image" onerror="alert(\'XSS Attack\')">';
const sanitizedInput = DOMPurify.sanitize(userInput); // Using a library like DOMPurify for sanitization
postSection.innerHTML = sanitizedInput;

By using proper sanitization techniques (like DOMPurify or other trusted sanitization libraries), you can mitigate the risk of XSS attacks when dynamically injecting content into the DOM via innerHTML.

Short Summary:

  • innerHTML: when dealing with HTML content manipulation.
  • innerText: when you need to manipulate or retrieve only visible text content on the screen.
  • textContent: when you want to handle raw text content that has formatting applied and want to ignore it’s styling considerations.
  • Always validate and sanitize any user-generated or untrusted data before injecting it into the DOM to prevent such security vulnerabilities.

You can use the three properties innerHTML, innerText, and textContent to manipulate the content of DOM elements. But they behave differently. Understanding them will help you decide when it's appropriate to use each one.

Adios!

Please consider showing your appreciation by providing feedback or suggestions in the comments and if you are pleased too much, you can always buy me a coffee 😉

buy me a coffee link

Thanks for reading till the end!

You can read some of my other posts:

--

--

Mohith Gupta

A Better Person than Yesterday, I guess? In the process of Learning