0

When writing something to HTML, we usually use: document.write(); ("D" is lowercase).

However, MDN docs describes the method as Document.write(); ("D" is uppercase), and it doesn't work when i tried testing it.

Can anyone help explain why this happened?

Sergio Flores
  • 5,231
  • 5
  • 37
  • 60

1 Answers1

1

In the same way you might see someone referencing Array.find (when in fact .find only exists on Array.prototype), .write exists on the prototype of Document, not on the Document constructor itself.

console.log(Document.prototype.hasOwnProperty('write'));

document.write works because document inherits from Document.prototype.

MDN's usage of Document.write is meant to convey that .write can be called on any instance of Document, even though the document constructor itself doesn't have that property.

It's possible to call .write from the prototype, if you wanted:

Document.prototype.write.call(
  document, // call on *this HTML document*
  '<div>foobar</div>' // first argument passed to .write
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • i understand partly what you say, but still a few question: 1, i cann't find trails of the relation of document to Document.prototype in MDN, is this relation self existed? 2, i tried {new Document().write()} which also not working. (but new Document() is an instance of Document which should contain the write() method); 3, i am a newbie language learner, hope not making fool question. – glitch bugg Feb 20 '21 at 19:33
  • Only HTML documents can have `.write` called on them; `new Document` won't be enough. (yeah, it'd odd that `.write` exists in Document and not on HTMLDocument) You can use something like [`createHTMLDocument`](https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument) if you want – CertainPerformance Feb 20 '21 at 23:26