5

That is, why do we not follow the standard JavaScript convention of using

var el = new Element("div");

but use

var el = document.createElement("div");

to do it?

(P.S. document is an object of the class Document. Element is also a class, and both Document and Element class are defined in the browser environment).

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • 4
    Because it is not part of Javascript but part of the DOM which are two separate things. – Christoph Apr 15 '13 at 11:51
  • 2
    check this http://stackoverflow.com/questions/6241716/is-there-a-difference-between-new-image-and-document-createelementimg – Tommi Apr 15 '13 at 11:52
  • 1
    @Christoph but `Element` is just like `document` that they are both in the browser environment – nonopolarity Apr 15 '13 at 17:49

2 Answers2

4

All of the document.xxxx methods are part of the DOM, not part of the Javascript language. It's a separate API that belongs to the browser, but which Javascript in the browser is allowed to access.

If another language were to be implemented in the browser, it would use the exact same API to access the DOM. In fact, VBScript in IE does exactly this - for proof, see some example code here. (but note, I'm not recommending actually using VBScript in a browser! Stick with JS)

And Javascript can be used outside of a browser environment (eg node.js), in which case it may not have or need a DOM class structure.

The DOM may also be implemented outside of a browser, and the same API would be available to any languages that use use it. For example, PHP has a DOMDocument class, which implements all the same DOM methods to add/remove/etc elements from the tree.

Spudley
  • 166,037
  • 39
  • 233
  • 307
2

The way I see this is that Javascript as a language needs to be agnostic to third party control structures. In this case the DOM, adding a new element to DOM should be managed by its control object document not via the language new Element("div").

In node.js there is no concept of DOM elements and therefore built in DOM control would be redundant in the language. Abstracting the control and manipulation of the DOM within a browser therefore makes sense and should, therefore be managed by an abstracted object document rather than by control structures within the language.

David Barker
  • 14,484
  • 3
  • 48
  • 77