Which do I use? When? Why?
You aren't alone if you find it daunting on which of these to choose and the nuances between them. This post will help break down, and give you a better understanding of them and when it's appropriate for each to use.
The Breakdown
These all share basically the same core function - which is to pull the contents inside elements. It begins to vary when it comes to what content is grabbed, and how it is also rendered on the page.
We will start with a few comparisons between InnerText and TextContent:
Mainly, TextContent allows you to grab ALL elements, where as InnerText is only going to use what's considered human readable elements.
InnerText can read CSS styles and will display them, TextContent will only display the content without any styling.
Here's a photo example from MDN showing how innertext and textcontent display differently
MDN has great references for getting a deeper understanding of how these all relate to each other and how they differ as well. I highly recommend using that site as much as you can in general, although there is a lot of information to sift through - it is very reliable and thoroughly explained.
InnerHTML
This one gets a little more confusing, and I feel like depending on the person you ask, you will get different opinions as to how they feel about using it. InnerHTML will actually take the text and whatever html tags are attached with it and either replace them with your assigned content, or you can grab existing content and append new contents to the existing one of an element. Take a look at MDN's documentation explaining the usage and DANGER'S of using InnerHTML over the other methods.
Top comments (0)