sententia
Home    Blog

textContent and innerText property in Firefox

From http://blog.coderlab.us/2006/04/18/the-textcontent-and-innertext-properties/

The textContent and innerText Properties

In my original post, Using the innerText Property in Firefox, I wrote my example using document.all to determine when to use innerText or textContent.

Because the main purpose of that post was to explain to the reader that Firefox does not support the innerText property but the textContent property, I failed to consider other browsers… yes, shame on me! (thanks Paul for bringing this to my attention).

You see, there are browsers that although don’t support document.all, they DO support the innerText property: Safari and Konqueror.

So, it is more efficient to check if the innerText property is supported by the user agent (thanks, Matthias). The way I do it is like this:

var hasInnerText =
(document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;
var elem = document.getElementById('id');
var elem2 = document.getElementById ('id2');

if(!hasInnerText){
    elem.textContent = value;
    elem2.textContent = value;
} else{
    elem.innerText = value;
    elem2.innerText = value;
}

Why am I using document.getElementsByTagName("body")[0]? Well, because, as you know, document.getElementsByTagName returns an array of elements with that tag name, and since there’s only ONE body tag, I’m calling the first and only index of that array at once. This is so, as you can see in the example above, if you have more than one element that you need to assign a value to.