What’s the difference between using .textContent vs .innerText vs .innerHTML?


All three of these properties are used to manipulate or get the text content of an element in HTML, but there are some important differences between them.

  1. textContent: This property returns the text content of an element without any HTML tags. It only considers the text of an element and ignores any formatting, like bold or italic text, or any HTML tags like <br>, <p>, <span>, etc. It will return all the text of an element, including text inside child elements.

Example:

<div id="example">
    This is some <b>bold text</b>.
</div>

Using textContent on the div element will return "This is some bold text.".

  1. innerText: This property also returns the text content of an element, but it includes any formatting, like bold or italic text. However, it still ignores any HTML tags like <br>, <p>, <span>, etc. It also returns only the visible text of an element, i.e., it excludes text inside elements with the display: none style property.

Example:

<div id="example">
    This is some <b>bold text</b>.
</div>

Using innerText on the div element will return "This is some bold text.".

  1. innerHTML: This property returns the HTML content of an element, including any HTML tags, attributes, and the text content. It also includes any child elements of the element. Using innerHTML to set the content of an element can be dangerous because it allows for the injection of arbitrary HTML code, which can lead to security vulnerabilities like cross-site scripting (XSS) attacks.

Example:

<div id="example">
    This is some <b>bold text</b>.
</div>

Using innerHTML on the div element will return "This is some <b>bold text</b>.".

In general, it is recommended to use textContent or innerText instead of innerHTML when you only need to manipulate or get the text content of an element, to avoid any security issues that may arise from the use of innerHTML.