Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Niet the Dark Absol Avatar asked Nov 18 '10 01:11

Niet the Dark Absol


1 Answers

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/

like image 142
SLaks Avatar answered Oct 28 '22 12:10

SLaks