InnerText and TextContent

Jackson Beytebiere
2 min readOct 19, 2020

--

innerText vs textContent

Short answer: innerText is what is rendered to the user while textContent shows everything, visible or hidden, including <style> and <script> elements. Heres a simple example:

from https://kellegous.com/j/2013/02/27/innertext-vs-textcontent/

An inquisitive programmer may look the two javascript properties innerText and textContent and wonder, what is the difference?

I encountered a problem while coding thru a lab while attending Flatiron. The instructions stated that using innerText to modify DOM element content would not work. How could this be? Doesn’t innerText do exactly what I think is does? Why would textContent work in its place?

First, a little history. Internet explorer introduced innerText and since then It has been widely adopted and adapted into other browsers for the sake of web backward compatibility. The foundational tenants of the Web states that one shall not break the web with new updates. Though Mozilla has refused to adopt this quirky property and the browser Opera computes textContent when you try to use innerText. Why the contention over innerText?

Well, innerText shows the user exactly what they would see. It renders the layout before it shows to the user. TextContent meanwhile will just give a straight up answer of the whole element with minimal computation needed. This gives textContent a huge advantage over innerText with computational speed (up to 300x as fast). That is why its recommended to always use textContent when possible. A case for using innerText could be working with rich text elements like in a text editor with a spellchecker, or a copy and paste functionality where the text that is copied should look exactly like what the user sees.

Some programmers advise others to steer clear of innerText whenever possible. such as software engineer Kelly Norton, who did a study on the computational speed of InnerText vs textContent. He refers to innerText as a “browser landmine” because of its ability to greatly slow down a webpage.

In summary, textContent is superior in most situations. One should use textContent when possible in order to create efficient code that will work across all browsers predictably.

--

--

Jackson Beytebiere
Jackson Beytebiere

Written by Jackson Beytebiere

I write about programming and specifically CSS | HTML | JavaScript | Ruby | React.js | Redux.

No responses yet