In Javascript, can you extend the DOM?

Solution 1:

I found the answer just as I was writing the question, but thought I'd post anyway to share the info.

The object you need to extend is Element.prototype.

Element.prototype.getMyId = function() {
    return this.id;
};

Solution 2:

you can extend the DOM by using the Element's prototype. However, this does not work in IE7 and earlier. You will need to extend the specific element, one at a time. The Prototype library does this. I recommend looking through the source to see exactly how it's done.

Solution 3:

You shouldn't be directly extending anything (by "anything" I mean native DOM objects) - that will only lead to bad things. Plus re-extending every new element (something you'd have to do to support IE) adds additional overhead.

Why not take the jQuery approach and create a wrapper/constructor and extend that instead:

var myDOM = (function(){
    var myDOM = function(elems){
            return new MyDOMConstruct(elems);
        },
        MyDOMConstruct = function(elems) {
            this.collection = elems[1] ? Array.prototype.slice.call(elems) : [elems];
            return this;
        };
    myDOM.fn = MyDOMConstruct.prototype = {
        forEach : function(fn) {
            var elems = this.collection;
            for (var i = 0, l = elems.length; i < l; i++) {
                fn( elems[i], i );
            }
            return this;
        },
        addStyles : function(styles) {
            var elems = this.collection;
            for (var i = 0, l = elems.length; i < l; i++) {
                for (var prop in styles) {
                    elems[i].style[prop] = styles[prop];
                }
            }
            return this;
        }
    };
    return myDOM;
})();

Then you can add your own methods via myDOM.fn ... And you can use it like this:

myDOM(document.getElementsByTagName('*')).forEach(function(elem){
    myDOM(elem).addStyles({
        color: 'red',
        backgroundColor : 'blue'
    });
});

Solution 4:

Yes you can, but it is strongly advised not to.

If you override something another library is expecting to be the original or another library overwrote something you were expecting .. chaos!

It is best practice to keep your code in your own namespace/scope.