Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
Nope Avatar asked Oct 02 '12 11:10

Nope


People also ask

What is the use of document object in HTML?

The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

What is the use of document object in JavaScript?

The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object.

What is document keyword in JavaScript?

In JavaScript (not just jQuery, but all JavaScript) the document keyword is a handle on the object that contains the HTMLDocument.

How do we get the DOM object in JavaScript?

The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element).


1 Answers

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");
like image 165
Konstantin Dinev Avatar answered Sep 22 '22 02:09

Konstantin Dinev