EN
JavaScript - textContent vs innerText
0
points
In this article, we would like to show you textContent and innerText differences in JavaScript.
| textContent | innerText |
|---|---|
became standard earlier than innerText | initially was not standard |
| returns the full text of the node (Example 1) | returns only the visible (rendered) text contained in a node (Example 1) |
ignores <br> elements | turns <br> elements into newline characters (\n) |
| is the only one available for text nodes (Example 2) | is defined only for HTMLElement objects |
| was unavailable in IE8 and earlier | is heavier than textContent in terms of performance (requires layout information to determine how the text is being presented to the user) |
More differences
- There's a difference in behavior between the
textContentandinnerTextwhen you change thetext-transformCSS property of an element. (Example 3)
Practical examples
Example 1
In this example, we create a div element with some text and a hidden span to show the difference in values returned by textContent and innerText.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container">
<div>Example
text...</div><span style="visibility:hidden">hidden text</span></div>
<script>
var container = document.querySelector('#container');
console.log('textContent: "' + container.textContent + '"');
console.log('innerText: "' + container.innerText + '"');
</script>
</body>
</html>
Example 2
Only the textContent is available for text nodes, innerText returns undefined.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
var textNode = document.createTextNode('Example text...');
console.log(textNode.textContent); // Example text...
console.log(textNode.innerText); // undefined
</script>
</body>
</html>
Example 3
In this example, we change the div element's text-transform style to show the difference in values returned by textContent and innerText.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="container" style="text-transform: uppercase;">Example text...</div>
<script>
var container = document.querySelector('#container');
console.log('textContent: "' + container.textContent + '"');
console.log('innerText: "' + container.innerText + '"');
</script>
</body>
</html>