Martin Honnen wrote:
Jason Keirstead wrote:
Is there a way I can add a setter/getter to the HTMLElement prototype
in internet explorer?
This, for example, works fine in Mozilla:
HTMLElement.prototype.__defineSetter__("foobar", function (sFoobar)
{
alert( sFoobar );
});
Of course my method I want to add is more complex, the question is is
there any way at all to do this in IE6?
There is no
HTMLElement
exposed in IE's object model, there is no prototype for host objects
exposed in IE's object model, and the JScript engine doesn't support
__defineSetter__ as that is a JavaScript 1.5 extension to the ECMAScript
standard.
Although the following is possible:
<script type="text/javascript">
var type, elements;
if (((type = typeof document.getElementsByTagName) == 'function' ||
(type == 'object' && document.getElementsByTagName)) &&
!!(elements = document.getElementsByTagName('*'))) {
var i = elements.length;
while (i--) {
elements[i].setFoobar = function(sFoobar) {
alert(this.nodeName + ';' + sFoobar);
}
}
}
document.body.setFoobar('this is a test');
</script>
Yes, I understand it is not the same as defining a setter for the
HTMLElement.prototype, but it does allow you to attach a method to every
element on the page, and it works in IE6SP1, Gecko-based browsers (Firefox,
Mozilla, Camino, Netscape 6+) and Opera 7.54. It even works in Opera 6.05,
although nodeName returns "undefined" so it is of limited usefulness there.
Of course any new elements added to the page programmatically will not have
the function as part of it's prototype, although you could add the function
when you construct the element:
var myDiv = document.createElement("div");
myDiv.setFoobar = function(sFoobar) {
alert(this.nodeName + ';' + sFoobar);
}
That condition would probably be clearer written as:
var type = typeof document.getElementsByTagName;
if (type == 'function' || (type == 'object' &&
document.getElementsByTagName) {
var elements = document.getElementsByTagName('*');
if (elements) {
// ...
}
}
Lastly. Of course my code can have a dramatic impact on performance on a
complex page. However, I have my doubts that you would need a setter on
*every* HTML element on the page, perhaps you would only want it on 3 or 4
nodeNames. In that case, it would probably be best to retrieve
document.getElementsByTagName('div'), 'td', 'a', etc for only the nodeNames
you actually need the setter attached to.
--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ -
http://jibbering.com/faq