innerText / textContent与检索每个文本节点 [英] innerText/textContent vs. retrieving each text node

查看:122
本文介绍了innerText / textContent与检索每个文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

例如

<div id="x">foo <em>foo...</em> foo</div>

结果:

getText(document.getElementById('x')); // => "foo foo... foo"

我相当肯定那里是使用 innerText textContent 的问题,但我无法在任何地方找到确定的列表,而我开始怀疑是否只是传闻。

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.

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

Can anyone offer any information about the possibly lacking reliability of textContent/innerText?

编辑:Kangax发现了这个好的答案 - 'innerText'在IE中工作,但不在Firefox中

EDIT: Found this great answer by Kangax -- 'innerText' works in IE, but not in Firefox

推荐答案

这是关于终端和空白 - 浏览器在这方面是非常不一致的,特别是在Internet Explorer中。执行遍历是在所有浏览器中获得相同结果的确定方式。

It's all about endlines and whitespace - browsers are very inconsistent in this regard, especially so in Internet Explorer. Doing the traversal is a sure-fire way to get identical results in all browsers.

这篇关于innerText / textContent与检索每个文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆