adding innerText to Mozilla and other browsers
Earlier today Scott Hanselman posted a reg-ex based solution that would allow a Mozilla based browser to return the innerText of a given element. The innerText property is specific to Internet Explorers DOM. I hate, *HATE* calling static methods to do validation or emulate things that should be rightfully in the object I'm dealing with. This isn't to say that the solution he posted is either good or bad, but you end up having to call this funtion all over in your code. I thought there should be a way to use the W3C DOM level 3 textContent property to emulate the innerText property in Mozilla based browsers using ECMAScripts prototype functionality.. Well, I was half-right. There was a way to prototype the innerText property. But the textContent property wasn't quite the correct way to go. I found the solution here.
Here is a short example of the innerText prototype in action.
-
<script language="JavaScript">
-
<!--
-
-
if((typeof HTMLElement != 'undefined') && HTMLElement.prototype.__defineGetter__ != 'undefined'))
-
{
-
HTMLElement.prototype.__defineGetter__("innerText", function () {
-
var r = this.ownerDocument.createRange();
-
r.selectNodeContents(this);
-
return r.toString();
-
});
-
}
-
-
function checkIt()
-
{
-
var hootie = document.getElementById("foo");
-
alert(hootie.innerText);
-
}
-
//-->
-
</script>
-
-
<body>
-
<form method=post action="">
-
<div id="foo">Hello World</div><br />
-
<input type="button" onClick="javascript:checkIt();"/>
-
</form>
-
</body>
As an aside, I'm starting to love the W3C DOM level 3. Things like being able to define your own getters and setters for DOM objects is great for writing a cross-browser emulation layer.
edited to clean up the code a little bit
update, here is a setter implimentation taken from the site that appears to be down. Thanks Google cache!
The setter is really simpe. If you think about what innerText is doing, and realize that the innerHTML property is the same except that it has a few extra characters. What you have to do becomes pretty clear.
HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
this.innerHTML = sText.replace(/\&/g, "&").replace(//g, ">");
});



Pingback: Dino Esposito's WebLog
Pingback: GOOK’s Blog » Blog Archive » IE 이?? ?라? ???? innerText ????기