kangax wrote:
> RobG wrote:
> [...]
>> Note that it will also return the content of script elements in some
>> browsers. Also, some browsers support both innerText and textContent
>> and may return a different value for each.
> I just noticed that Safari 2 - 2.0.4 (and maybe earlier) actually has
> `innerText` but that `innerText` is always an empty string : /
My mistake.
Safari *does* return "proper" `innerText` but only if an element is
neither hidden nor orphaned (there was an element with "display:none" in
my test). Considering these 2 "issues", the method, unfortunately,
becomes even more complex (still without proper script element handling).
I'm not sure if such "forking" is worth the trouble. Recursively
collecting node values would produce more consistent results, albeit
being slower.
var getInnerText = (function(){
function f(element) {
return null;
}
if (document.createElement && document.createTextNode) {
var root = (document.body || document.documentElement);
var testee = document.createElement('div');
var textNode = document.createTextNode('x');
if (root && testee && testee.appendChild && textNode) {
// Safari 2.x returns empty string as `innerText`
// of an orphaned element
// so we append it to a document temporarily
testee.appendChild(textNode);
root.appendChild(testee);
if (typeof testee.textContent == 'string' &&
testee.textContent == 'x') {
f = function(element) {
return element.textContent;
}
} else if (typeof testee.innerText == 'string' &&
testee.innerText == 'x') {
// store
var value = testee.style.display;
testee.style.display = 'none';
// test
var HIDDEN_ELEMENTS_ARE_BUGGY = (testee.innerText !== 'x');
// restore
testee.style.display = value;
if (HIDDEN_ELEMENTS_ARE_BUGGY) {
f = function(element) {
var el = element, values = [ ];
// display all ancestors
while (element && element.style) {
values.push(element.style.display);
element.style.display = '';
element = element.parentNode;
}
// get value
var s = el.innerText;
// restore ancestors' display value
while (element && element.style) {
element.style.display = values.shift();
element = element.parentNode;
}
return s;
}
}
else {
f = function(element) {
return element.innerText;
}
}
} else {
f = function(element) {
function getChildren(parent) {
var child = parent.firstChild;
while (child) {
if (child.nodeType == 3) {
result.push(child.nodeValue);
}
else {
getChildren(child);
}
child = child.nextSibling;
}
}
var result = [];
getChildren(element);
return result.join('');
}
}
root.removeChild(testee);
testee = null;
}
}
return f;
})();
--
kangax