问题
Possible Duplicate:
How does jQuery’s .text() work, internally?
I'm looking for the text equivalent of innerHTML
, i.e.
<p>Hello, <i>World!</i></p>
then innerText(p)
should return Hello, World!
.
Note: I'm aware of jQuery's text()
function. I want to know how it is implemented so I can do special handling on some nodes, like inserting extra white space.
回答1:
how about this?
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;
};
then: var innerText = getInnerText(myElement);
jsfiddle
回答2:
Here is the source for getText(): Taken from question: 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;
};
回答3:
use innerText property instead of innetHTML.
Example...
<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>
来源:https://stackoverflow.com/questions/12895152/equivalent-of-innerhtml-for-text