What is the difference between innerHTML
, innerText
and childNodes[].value
in JavaScript?
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.
to add to the list, innerText will keep your text-transform, innerHTML wont
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;
.name{
color:red;
}
<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 simple words:
innerText
will show the value as is and ignores any HTML
formatting which may
be included.innerHTML
will show the value and apply any HTML
formatting.InnerText
will only return the text value of the page with each element on a newline in plain text, while innerHTML
will return the HTML content of everything inside the body
tag, and childNodes
will return a list of nodes, as the name suggests.