Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, why do we use el = document.createElement() to create an Element object instead of el = new Element();

Tags:

javascript

dom

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).

like image 851
nonopolarity Avatar asked Apr 15 '13 11:04

nonopolarity


1 Answers

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.

like image 140
Spudley Avatar answered Oct 11 '22 15:10

Spudley