Search code examples
javascriptprototype

How can I extend the document object?


I'm currently trying to get a better understanding of JavaScript and prototyping.

I wanted to add a function to the document but prototype is undefined on document.

This code:

document.prototype.writeLine = function(text){
    this.write(text);
    this.write("<br />");  
};

Generates this error:

// In FireFox
TypeError: document.prototype is undefined

// In Chrome
Uncaught TypeError: Cannot set property 'writeLine' of undefined 

How can I extend the document object to be able to call something similar to document.WriteLine('MyText') ?

Here is the Fiddle I'm working with.


Solution

  • I updated your fiddle. The problem you were having is that document object is an instance of the HTMLDocument object type. The instance itself doesn't have a prototype, however the HTMLDocument does.

    Update: Here is a snippet which works in IE9 because under IE9 HTMLDocument is undefined.

    if (typeof HTMLDocument !== 'undefined') {
        HTMLDocument.prototype.writeLine = function(text){
            this.write(text);
            this.write("<br />");  
        };
    } else {
        Document.prototype.writeLine = function(text){
            this.write(text);
            this.write("<br />");  
        };
    }
    
    document.writeLine("Line 1");
    document.writeLine("Line 2");