What is the difference between textContent
and innerText
in JavaScript?
Can I use textContent
as follows:
var logo$ = document.getElementsByClassName('logo')[0]; logo$.textContent = "Example";
Additional notes. innerText retrieves and sets the content of the tag as plain text, where innerHTML retrieves and sets the same content in HTML format.
value is for form elements to get the value of the form element. input. textContent is for other elements to get the content of the element.
Basically, innerText: what's between the tags of the element. outerText: content of the element, including the tags.
The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.
The key differences between innerText
and textContent
are outlined very well in Kelly Norton's blogpost: innerText vs. textContent. Below you can find a summary:
innerText
was non-standard, textContent
was standardized earlier.innerText
returns the visible text contained in a node, while textContent
returns the full text. For example, on the following HTML <span>Hello <span style="display: none;">World</span></span>
, innerText
will return 'Hello', while textContent
will return 'Hello World'. For a more complete list of differences, see the table at http://perfectionkills.com/the-poor-misunderstood-innerText/ (further reading at 'innerText' works in IE, but not in Firefox).innerText
is much more performance-heavy: it requires layout information to return the result.innerText
is defined only for HTMLElement
objects, while textContent
is defined for all Node
objects.Be sure to also have a look at the informative comments below this answer.
textContent
was unavailable in IE8-, and a bare-metal polyfill would have looked like a recursive function using nodeValue
on all childNodes
of the specified node:
function textContent(rootNode) { if ('textContent' in document.createTextNode('')) return rootNode.textContent; var childNodes = rootNode.childNodes, len = childNodes.length, result = ''; for (var i = 0; i < len; i++) { if (childNodes[i].nodeType === 3) result += childNodes[i].nodeValue; else if (childNodes[i].nodeType === 1) result += textContent(childNodes[i]); } return result; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With