JavaScript creating HTML5/XML element node

352 views Asked by At

To create an element to be used in a HTML5 document with JavaScript we can use the createElement() and createElementNS() methods from DOMDocument objects:

var node = document.createElement(element);
var node = document.createElementNS(nameSpace, element);

These commands create a node and than we can put it at some point of the document tree using appendChild(). My first question is: do the document.createElement() and document.createElementNS() functions store the node object they return at some place in the document object?

Second, is it possible to create an element node object (possibly using a name space) independent of specific document objects and later on to append it in the document tree of some documentobject given? That is, are there functions similar to createElement() and createElementNS() which are not members of a specific object (like the document object, as is the case above)?

Third, is it possible to create an element node object using a given document object document1 and them to append it on the document tree of another document object document2?

1

There are 1 answers

3
Carlo Cannas On BEST ANSWER

My first question is: do the document.createElement() and document.createElementNS() functions store the node object they return at some place in the document object?

No, the implementation may do something like that internally, but nothing like that is exposed externally.

is it possible to create an element node object (possibly using a name space) independent of specific document objects and later on to append it in the document tree of some documentobject given?

The answer to this question is also no: each element, in general, each node is bound to the document object used to create it, which is referenced by the ownerDocument property.

Third, is it possible to create an element node object using a given document object document1 and them to append it on the document tree of another document object document2?

Yes, the second document has to adopt the node, via the adoptNode method. With DOM4 this method will mostly become unnecessary, since it's primarily used before insert a foreign node in a document, and DOM4 specifies that the adoption in such case is implicit.