简体   繁体   中英

JavaScript creating HTML5/XML element node

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 document object 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM