用于文本的innerHTML的等价物

时间:2012-10-15 11:55:46

标签: javascript dom textnode

  

可能重复:
  How does jQuery’s .text() work, internally?

我正在寻找等同于innerHTML的文本,即

<p>Hello, <i>World!</i></p>

然后innerText(p)应该返回Hello, World!

注意:我知道jQuery的text()函数。我想知道它是如何实现的,所以我可以在某些节点上进行特殊处理,比如插入额外的空格。

3 个答案:

答案 0 :(得分:2)

以下是getText()的来源:摘自问题:How does jQuery’s .text() work, internally?

// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
    var ret = "", elem;

    for ( var i = 0; elems[i]; i++ ) {
        elem = elems[i];

        // Get the text from text nodes and CDATA nodes
        if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
            ret += elem.nodeValue;

        // Traverse everything else, except comment nodes
        } else if ( elem.nodeType !== 8 ) {
            ret += Sizzle.getText( elem.childNodes );
        }
    }

    return ret;
};

答案 1 :(得分:1)

怎么样?

var getInnerText = function (element) {
    var nodes = element.childNodes,
        i = 0,
        len = nodes.length,
        text = '';
    for (; i < len; i++) {
        if (nodes[i].nodeType === 3 || nodes[i].nodeType === 4) {
            // 3 means text node, 4 means cdata
            text += nodes[i].nodeValue;
        } else {
            text += getInnerText(nodes[i]);
        }
    }
    return text;
};

然后:var innerText = getInnerText(myElement);

jsfiddle

答案 2 :(得分:0)

使用innerText属性而不是innetHTML。

示例......

<html>
<body>
<p id="myP">Sample Text inside a <b>p</b> element <a href="#"> this is a link </a></p>
<button onclick="alert(myP.innerHTML);">InnerHTML</button>
<button onclick="alert(myP.innerText);">InnerText</button>
</body>
</html>