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

That is why we donโ€™t follow standard JavaScript usage conventions

var el = new Element("div"); 

but use

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

do it?

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

+4
source share
2 answers

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

If a different language was implemented in the browser, it will use the same API to access the DOM. In fact, VBScript in IE does just that - for proof, see the sample code here . (but note, I do not recommend using VBScript in the browser! Stick with JS)

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

The DOM can also be implemented outside the browser, and the same API will be available for any languages โ€‹โ€‹that use it. For example, PHP has a DOMDocument class that implements all the same DOM methods to add / remove / etc elements from a tree.

+4
source

As I see it, Javascript as a language should be agnostic for third-party control structures. In this case, the DOM, adding a new element to the DOM, must be controlled by its document control object not through the language of the new Element("div") .

There is no concept of DOM elements in node.js, so the built-in DOM control will be redundant in the language. Thus, the abstract control and manipulation of the DOM inside the browser makes sense and therefore should be controlled by the abstract document object, and not by the control structures inside the language.

+1
source

All Articles