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 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;
};
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>
<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>
Post a Comment for "Equivalent Of InnerHTML For Text"