Over a million developers have joined DZone.

JavaScript Gotcha: innerText

DZone's Guide to

JavaScript Gotcha: innerText

· Web Dev Zone ·
Free Resource

A true open source, API-first CMS — giving you the power to think outside the webpage. Try it for free.

Let's consider a scenario where you need to perform some basic text content manipulation on a web-page. For example, you would need to perform character verification based on an extracted value from another string. Roughly, something like this:

function selectSubText(startPoint, howMuchBack, charNumber) {
    var textC = document.getElementById("exerciseText");
    var data = textC.innerText;
    var text = data.substring(startPoint - howMuchBack + 1, startPoint + 1 + charNumber);

    return text;

So what's wrong with the snippet above? Try performing a "suffix check" on a string that ends with a break and another part starting from a new line. By "suffix check" I mean - check the next character after the one you have selected, given that the next character will be the one right after the last character before the line end. It will all ultimately rely on innerText.

We get a space and \r (carriage return) as the line delimiter in Internet Explorer. Let's test this in Chrome:

There is the first problem - there is a space, but no \r. What this means is that character detection can already be off, depending on the way you implemented line break detection. Let's see what happens in Firefox.

If you guessed that Firefox doesn't even work with innerText, you guessed correctly. Firefox relies on textContent instead, so if you plan on relying on innerText, also consider adding a browser check. 

Bottom line - by default textContent handles new lines with a simple \n, so for a consistent cross-browser experience, try to use it instead.

The New Standard for a Hybrid CMS: GraphQL Support, Scripting as a Service, SPA Support. Watch on-demand now.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}