Reputation: 324630
I have some JavaScript code that defines a function getElementsByAttribute
as follows:
Object.prototype.getElementsByAttribute = function(attr) {
var children = this.all || this.getElementsByTagName('*'),
ret = [], i, c;
for( i=0; i<children.length; i++) {
c = children[i].getAttribute(attr);
if( typeof c == "string" && c != "")
ret.push(children[i]);
}
return ret;
}
This works in all browsers I have tested in, except Internet Explorer 7 (and presumably lower) - these browers throw "Object doesn't support this property or method."
The only thing I can think of that it doesn't like that is the Objects have already been created when I defined the prototype function...
Shrot of defining the function as a... well, a "normal" function and passing the element as an argument, is there any way to make this work in IE7 and below?
Upvotes: 6
Views: 3688
Reputation: 35505
Adding things to Object.prototype
is a really bad idea. It will be added to every object, and that will cause unintended behavior, I guarantee it.
Simply define your function and decorate it onto whatever objects you need dynamically.
Upvotes: 1
Reputation: 887413
IE DOM elements aren't normal Javascript objects and do not inherit prototypes as you would expect.
http://perfectionkills.com/whats-wrong-with-extending-the-dom/
Upvotes: 6