innerText/textContent与检索每个文本节点

Jam*_*mes 32 javascript dom

我听说使用el.innerText||el.textContent可以产生不可靠的结果,这就是为什么我一直坚持使用以下功能:

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;

}
Run Code Online (Sandbox Code Playgroud)

此函数遍历元素中的所有节点,并收集所有文本节点的文本以及后代中的文本:

例如

<div id="x">foo <em>foo...</em> foo</div>
Run Code Online (Sandbox Code Playgroud)

结果:

getText(document.getElementById('x')); // => "foo foo... foo"
Run Code Online (Sandbox Code Playgroud)

确定使用innerText和存在问题textContent,但我无法在任何地方找到确定的列表,我开始怀疑它是否只是传闻.

任何人都可以提供有关textContent/innerText可能缺乏可靠性的任何信息吗?

编辑:发现Kangax的这个伟大的答案 - 'innerText'在IE中工作,但在Firefox中不起作用

Joh*_*sig 33

这一切都与端点和空白有关 - 浏览器在这方面非常不一致,特别是在Internet Explorer中.进行遍历是在所有浏览器中获得相同结果的可靠方法.

  • 遍历不保证在所有浏览器中都有相同的结果.例如,在IE中(与其他浏览器不同),`<script>`元素的内容不表示为DOM中的文本节点. (14认同)