innerText/textContent vs. retrieving each text node
Posted
by J-P
on Stack Overflow
See other posts from Stack Overflow
or by J-P
Published on 2010-04-16T14:27:16Z
Indexed on
2010/05/08
16:58 UTC
Read the original article
Hit count: 159
JavaScript
|dom
I've heard that using el.innerText||el.textContent
can yield unreliable results, and that's why I've always insisted on using the following function in the past:
function getText(node) {
if (node.nodeType === 3) {
return node.data;
}
var txt = '';
if (node = node.firstChild) do {
txt += getText(node);
} while (node = node.nextSibling);
return txt;
}
This function goes through all nodes within an element and gathers the text of all text nodes, and text within descendants:
E.g.
<div id="x">foo <em>foo...</em> foo</div>
Result:
getText(document.getElementById('x')); // => "foo foo... foo"
I'm quite sure there are issues with using innerText
and textContent
, but I've not been able to find a definitive list anywhere and I am starting to wonder if it's just hearsay.
Can anyone offer any information about the possibly lacking reliability of textContent/innerText?
EDIT: Found this great answer by Kangax -- http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox/1359822#1359822
© Stack Overflow or respective owner