Extending the DOM interfaces

H

Henri Sivonen

In order to keep subsequent code clear, I added a new method like this

HTMLDivElement.prototype.foo = function(arg) {
// foo for HTML div trees
}

Element.prototype.foo = function(arg) {
// foo for XML tree retrieved using XMLHttpRequest
}

Since I had used the same approach for extending Array in IE 5.0, I
thought this was a cross-browser compatible approach. I was so naïve!
It seems this works in gecko-based browsers only.

Is there a trick for making this work in IE 6, Safari and Opera 8? Or
should I write two functions like this
function fooHtml(elt, arg) {
// ...
}
function fooXml(elt, arg) {
// ...
}
?
 
C

Csaba Gabor

I commiserate with you...

There was a related discussion (Attaching a method to DOM elements - March 7) at
http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/cf9d3cfb75c080f7/

which was kicked off by Funky function assignment question (Firefox vs. IE)
http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/df5e2bbfa81aa1f7/

I am very skeptical about the speed of the offered IE method, besides objecting
to having to provide an extra file. I guess one should do experiments to see
whether the attachment in the IE method attaches the function to each
instance or not. If so, may as well just iterate through with javascript.

Csaba Gabor from Vienna
 
M

Martin Honnen

Henri said:
In order to keep subsequent code clear, I added a new method like this

HTMLDivElement.prototype.foo = function(arg) {
// foo for HTML div trees
}

Since I had used the same approach for extending Array in IE 5.0, I
thought this was a cross-browser compatible approach. I was so naïve!
It seems this works in gecko-based browsers only.

Array is a native object in ECMAScript and for those the constructor
functions and the prototypes are exposed and properties and methods can
be added. But <div> element objects are host objects, and the ECMAScript
specification doesn't in any way require that constructor functions of
host objects are exposed. Nor does the W3C DOM ECMAScript binding, there
are only a few interfaces where you could read that binding as requiring
the constructor function to be exposed to have static properties like
node type constants.
Is there a trick for making this work in IE 6, Safari and Opera 8? Or
should I write two functions like this
function fooHtml(elt, arg) {
// ...
}
function fooXml(elt, arg) {
// ...
}
?

If you want to cover all those browsers you probably need to use that
approach with functions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top