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.
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.
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.
In JavaScript (not just jQuery, but all JavaScript) the document keyword is a handle on the object that contains the HTMLDocument.
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).
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With