Over a million developers have joined DZone.
Platinum Partner

JavaScript Gotcha: innerText

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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 in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}