Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Object.prototype in JavaScript

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

Answers (2)

Adam Lassek
Adam Lassek

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

SLaks
SLaks

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

Related Questions