What is the difference between innerHTML
, innerText
and childNodes[].value
in JavaScript?
The examples below refer to the following HTML snippet:
Warning: This element contains code
and strong language.
The node will be referenced by the following JavaScript:
var x = document.getElementById('test');
element.innerHTML
Sets or gets the HTML syntax describing the element's descendants
x.innerHTML
// => "
// => Warning: This element contains code
and strong language.
// => "
This is part of the W3C's DOM Parsing and Serialization Specification. Note it's a property of Element
objects.
node.innerText
Sets or gets the text between the start and end tags of the object
x.innerText
// => "Warning: This element contains code and strong language."
innerText
was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016, innerText
was adopted by the WHATWG and was added to Firefox in v45.innerText
gives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means:
innerText
applies text-transform
and white-space
rulesinnerText
trims white space between lines and adds line breaks between itemsinnerText
will not return text for invisible itemsinnerText
will return textContent
for elements that are never rendered like
and ` Node
elements
node.textContent
Gets or sets the text content of a node and its descendants.
x.textContent
// => "
// => Warning: This element contains code and strong language.
// => "
While this is a W3C standard, it is not supported by IE < 9.
Node
elements
node.value
This one depends on the element that you've targeted. For the above example, x
returns an HTMLDivElement object, which does not have a value
property defined.
x.value // => null
Input tags (), for example, do define a value property, which refers to the "current value in the control".
From the docs:
Note: for certain input types the returned value might not match the value the user has entered. For example, if the user enters a non-numeric value into an
, the returned value might be an empty string instead.
Here's an example which shows the output for the HTML presented above:
var properties = ['innerHTML', 'innerText', 'textContent', 'value'];
// Writes to textarea#output and console
function log(obj) {
console.log(obj);
var currValue = document.getElementById('output').value;
document.getElementById('output').value = (currValue ? currValue + '\n' : '') + obj;
}
// Logs property as [propName]value[/propertyName]
function logProperty(obj, property) {
var value = obj[property];
log('[' + property + ']' + value + '[/' + property + ']');
}
// Main
log('=============== ' + properties.join(' ') + ' ===============');
for (var i = 0; i < properties.length; i++) {
logProperty(document.getElementById('test'), properties[i]);
}
Warning: This element contains code
and strong language.