Getting innerText to work in Firefox and return/set only first node of jQuery.text()

Firefox uses the W3C-compliant textContent property instead of innerText. Most other browsers, such as Chrome and IE, use innerText and, to make things worse, IE does not support innerText. Also, when using jQuery.text(), all text inside the node plus its child nodes are returned, which is not the same as innerText or textContent. To get around this, I wrote a small jQuery plug-in.

The code

(function( $ ) {
$.fn.innerText
= function(text) {
var ff = (typeof this[0].textContent !== "undefined");
if (text) {
if (ff) {
this[0].textContent = text;
}
else {
this[0].innerText = text;
}
}
else {
return (ff) ? this[0].textContent : this[0].innerText;
}

return this;
};
}( jQuery ));

Add the code in your page or within a script file and include it as a reference after the jQuery reference.

The amendments

You need to slightly amend your code to the following as you are following jQuery syntax.

// Get the value
var value = $("#object1").innerText();
// Set the value
$("#object1").innerText("My new text value");

Futher info

For a real deep dive in the issue, see “The poor, misunderstood innerText” on Perfection Kills.