Friday, July 21, 2006

Simulating IE4+ Syntax in NN6 (Simulating innerText and outerHTML)

As I explained that we can create simulate/create new properties for static objects in NN6. Here is how we can simulate "innerText" and "outerHTML" which are supported by IE4+ but not by NN6.


if (HTMLElement)
{
HTMLElement.prototype.__defineSetter__("innerText", function (txt)

{
var rng = document.createRange();
rng.selectNodeContents(this);
rng.deleteContents();
var newText = document.createTextNode(txt);
this.appendChild(newText);
return txt;
})
HTMLElement.prototype.__defineGetter__("innerText", function ()
{
var rng = document.createRange();
rng.selectNode(this);
return rng.toString();
})

HTMLElement.prototype.__defineSetter__("outerHTML", function (html)
{
var rng = document.createRange();
rng.selectNode(this);
var newHTML = rng.createContextualFragment(html);
this.parentNode.replaceChild(newHTML,this);
return html;
})
HTMLElement.prototype.__defineGetter__("outerHTML", function() {return ‘’})
}



The getter function for the innerText property creates a range whose boundaries encompass the current object. Because a range includes only the text part of a document, the adjustment of the range boundaries to the current node encompasses all text, including text nodes of nested elements. Returning the string version of the range provides a copy of all text inside the current element. For the setter action, the anonymous function defines one parameter variable, which is the text to replace the text inside an element. With the help, again, of the Range object, the range is cinched up to encompass the contents of the current node. Those contents are deleted, and new text node is created out of the value assigned to the property (in other words, passed as a parameter to the anonymous function). With the current object no longer containing any nodes after the deletion, the appendChild() method inserts the new text node as a child to the current
object.

Setting the outerHTML property starts out the same as setting the innerText, but the new content—which arrives as a string assigned to the parameter variable—is converted into a fully formed set of nested nodes via the createContextualFragment() method. This method is invoked on any range object, but it does not affect the range to which it is attached. The value returned from the method is what’s important, containing a node whose content is already set up as genuine DOM nodes. That’s why the returned value can be passed to the replaceChild() method to replace the new content as HTML rather than plain text. But because the outerHTML property applies to the entire current element, it must use the roundabout way of replacing itself as a child of its parent. This prevents the accidental modification of any siblings in the process.

No comments:

Post a Comment

Feel free to give constructive feedback or let me know if it was helpful.