DEV Community

loren-michael
loren-michael

Posted on

innerText vs textContent

As I was going through some lessons about manipulating the DOM, we were presented with two ways to change the text of a node (or, more commonly, an HTML element):

.innerText
and
.textContent

While their functions appear to be similar - take the text in an node and change it to something else - they actually work pretty differently when taking a closer look.

Let's start with .textContent

From what I've learned so far, this method will return the text in a node while also taking spacing into consideration. It will give you all of the raw text inside the node, including some text that might be hidden from users. It also can be used on all node objects.

Moving on to .innerText

When you use .innerText, you will have returned to you only the text inside the node returned to you without any additional spacing included. It will only give you the visible text that gets shown to users. Interestingly, because of the way that .innerText takes the extra computing time to look at the layout, it can feel sluggish and is more demanding on your system.

Looking at them side by side, it seems that using .textContent is generally the habit you want to create when you're changing some text in your DOM.

Oh, and I haven't really learned about .innerHTML yet, but maybe when it comes up I'll revisit and compare all three together.

Top comments (1)

Collapse
 
kolja profile image
Kolja

Thx