Over a million developers have joined DZone.

JavaScript Gotcha: innerText

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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 Web Dev Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".


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

{{ parent.tldr }}

{{ parent.urlSource.name }}