You would think textContents, innerText, and innerHTML would work the same way in JavaScript. There are so many ways to accomplish the same thing while coding, that this is just another. You would be wrong, all three of these render different output when using them.
Here’s an example of some simple HTML with some inline CSS:
Here is what that looks like opened up in the browser:
As you can see the word ‘emphasized’ is in italics and the word ‘code’ monospaced. For those wondering monospaced means all or most the characters take up the same amount of horizontal space. In a console we set a const to our div and call that const with ‘.innerHTML’:
Using innerHTML shows you everything in the HTML markup contained in a string. This includes elements like spacing, line breaks and formatting. As you can see in the example above we see the tags around the word emphasized making the word italic, we are also shown the 6 spaces between ‘emphasized’ and ‘and’, and lastly we see the tags. You should only use innerHTML when you want to see the HTML markup and what is in the element.
Using innerText returns the string inside the div, it renders the text content of a node and knows about the styling and CSS. In the example above we again set the div to a const and then call it with ‘.innerText’. The return is exactly the same as it appears in the browser. You do not see the spacing oddity or the and tags. Use innerText when you only want to see the element.
TextContent returns content of all elements in the node. Its aware if script and style elements, also formatting like spacing and line breaks. In the example above we set the div to a const and call on it with ‘.textContent’. The return is almost as it appears in the browser with the exception of the spacing. You should use textContent when you want to see what in an element plus any styling.
Some additional notes, in innerHTML if the text inside the element includes ‘&’, ‘<’, or ‘>’ they will be returned as HTML entities ‘&’, ‘<’ and ‘>’. Using innerText sets the content of the tag as plain text, in innerHTML it retrieves and sets the content in HTML format. The difference between innerText and textContent is that innerText is aware of it’s appearance and textContent is not.
Top comments (0)