Wednesday, January 11, 2006

Firefox innerText

I just implemented a method to get innerText. It's for a complicated document.


function ccGetMZInnerText(element) {

var innerText = "";
if (element.hasChildNodes()) {

var displayType = window.getComputedStyle(element,null).getPropertyValue("display");
if (displayType != null && displayType!="none") {
for (var i = 0; i <>
if (element.tagName=="P") innerText = "\n" + innerText;
innerText = innerText + ccGetMZInnerText( element.childNodes[i] );
}
if (displayType!="inline") innerText = innerText + "\n";
}

} else {

if ( element.nodeType == 3 ) {// text
innerText = innerText + ccTextCorrection(element.nodeValue);
} else if (element.nodeType == 1) { //object
var displayType = window.getComputedStyle(element,null).getPropertyValue("display");
if (displayType == null || displayType=="none") {
} else if (displayType=="inline") {
innerText = innerText + ccTextCorrection(element.textContent);
if (element.tagName=="BR") innerText = innerText + "\n";
} else {
innerText = innerText + ccTextCorrection(element.textContent) + "\n";
}
}

}

return innerText;

}

function ccTextCorrection(fooString) { //replace to blank, and remove line break.
return fooString.replace(/ /g, " ").replace(/\n/g, "").replace(/\r/g, "");
}

2 comments:

Alex said...

Please try the following sample.

<DIV id="fooBody">
<STYLE type="text/css">
A {color:red}
</STYLE>
<SCRIPT language="JavaScript" type="text/javascript">
document.write("text");
</SCRIPT>
<BR>

<P>
this is a test
this is a test
</P>
</DIV>

<BUTTON onClick="ccGetText()">Get Text</BUTTON>

function ccGetText() {
var object = document.getElementById("fooBody");
var innerText = ccGetMZInnerText(object);
}

Daniel Markham said...

Alex.

This looks like it could be a nice tool for the toolbelt (I take it that textContent is not so good?)

But it doesn't run. JSLint barfs on it. Something about your for loop -- it looks like you are missing some stuff there.

Let me know if you update the posting. I'd like to try it out on some of my stuff if that is okay with you.