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) |
- There's a difference in behavior between the
textContent
andinnerText
when you change thetext-transform
CSS property of an element. (Example 3)
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
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">
5
<div>Example
6
text...</div><span style="visibility:hidden">hidden text</span></div>
7
<script>
8
9
var container = document.querySelector('#container');
10
11
console.log('textContent: "' + container.textContent + '"');
12
console.log('innerText: "' + container.innerText + '"');
13
14
</script>
15
</body>
16
</html>
Only the textContent
is available for text nodes, innerText
returns undefined
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var textNode = document.createTextNode('Example text...');
7
8
console.log(textNode.textContent); // Example text...
9
console.log(textNode.innerText); // undefined
10
11
</script>
12
</body>
13
</html>
In this example, we change the div element's text-transform style to show the difference in values returned by textContent
and innerText
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container" style="text-transform: uppercase;">Example text...</div>
5
<script>
6
7
var container = document.querySelector('#container');
8
9
console.log('textContent: "' + container.textContent + '"');
10
console.log('innerText: "' + container.innerText + '"');
11
12
</script>
13
</body>
14
</html>