Equivalent Of Innerhtml For Text
Possible Duplicate: How does jQuery’s .text() work, internally? I'm looking for the text equivalent of innerHTML, i.e.
Hello, World!
theSolution 1:
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 nodesSizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodesif ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} elseif ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
Solution 2:
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);
Solution 3:
use innerText property instead of innetHTML.
Example...
<html><body><pid="myP">Sample Text inside a <b>p</b> element <ahref="#"> this is a link </a></p><buttononclick="alert(myP.innerHTML);">InnerHTML</button><buttononclick="alert(myP.innerText);">InnerText</button></body></html>
Post a Comment for "Equivalent Of Innerhtml For Text"