Difference between innerText, innerHTML, and childNodes[].value?


What is the difference between innerHTML, innerText and childNodes[].value in JavaScript?

8/24/2020 11:39:46 PM

Accepted Answer

Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the content in HTML format.

2/14/2018 6:09:52 AM

InnerText property html-encodes the content, turning <p> to &lt;p&gt;, etc. If you want to insert HTML tags you need to use InnerHTML.


In simple words:

  1. innerText will show the value as is and ignores any HTML formatting which may be included.
  2. innerHTML will show the value and apply any HTML formatting.

The only difference between innerText and innerHTML is that innerText insert string as it is into the element, while innerHTML run it as html content.

const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';
document.getElementById('innertext').innerText = ourstring;
document.getElementById('innerhtml').innerHTML = ourstring;
<h3>Inner text below. It inject string as it is into the element.</h3>
<div id="innertext"></div>
<br />
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>
<div id="innerhtml"></div>

var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);

To further refine it and retrieve the value Alec for example, use another .childNodes[1]

var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);

In terms of MutationObservers, setting innerHTML generates a childList mutation due to the browsers removing the node and then adding a new node with the value of innerHTML.

If you set innerText, a characterData mutation is generated.