Forum Moderators: open
I've got a bit of a problem.
I need to use the functionality of innerText as it "strips" out any HTML code tags and returns the actual text. E.g <b>snowman</b> becomes snowman.
I need to be able to do this and return the text part of a string, obviously it works with IE as they support the innerText, but I need a solution for NN/Mozilla browsers.
I hope this mkes sense, and I really need a solution fast.
Thanks for your help.
<script type="text/javascript">
var text = "<p id='foo'>This <strong>contains</strong> HTML <span>tags</span> to be replaced.</p>";
var htmlTag = /<\/{0,1}([A-Z][A-Z0-9]*)\b[^>]*>/gi;
text = text.replace(htmlTag,"");
alert(text);
</script>
[edited by: Fotiman at 3:58 pm (utc) on Mar. 14, 2007]
In any case, this should work for both IE and Mozilla:
var c = document.getElementById("container");
var text = ( c.textContent ¦¦ c.innerText );
alert( text );
Be sure to replace the ¦¦ with the pipe characters.
[edited by: Fotiman at 4:30 pm (utc) on Mar. 14, 2007]
Thanks for your suggestions, but I managed to resolve it, if anyone is interested here is the solution:
function getInnerText(o)
{
var txt='';
for (var i=0; i<o.childNodes.length; i++) {
switch(o.childNodes[i].nodeType) {
case 1 : txt += getInnerText(o.childNodes[i]); break
case 3 : txt += o.childNodes[i].nodeValue; break
case 8 : txt += "\n"; break
}
}
return txt;
}
And it works with both IE & NN!
:)
function getInnerText(o)
{
var txt='';
for (var i=0; i<o.childNodes.length; i++) {
switch(o.childNodes[i].nodeType) {
case 1 : txt += getInnerText(o.childNodes[i]); break
case 3 : txt += o.childNodes[i].nodeValue; break
case 8 : txt += "\n"; break
}
}
return txt;
}
Why would you want to do all of that? It's very inefficient, as you need to manually loop through all of the nested nodes. All of that can be replaced with this single line:
var txt = ( o.textContent ¦¦ o.innerText );
[edited by: Fotiman at 6:11 pm (utc) on Mar. 15, 2007]