.NET Zone is brought to you in partnership with:

Den is a DZone Zone Leader and has posted 460 posts at DZone. You can read more from them at their website. View Full User Profile

JavaScript Gotcha: innerText

04.12.2013
| 3177 views |
  • submit to reddit

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) {
    //debugger
    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.