1

in Javascript I wonder if I create an element without appending to child what will happen ? also what if I create the element from different doc and add it to new one ?

  var text, parser, xmlDoc;

text = "<bookstore></bookstore>";
var text2="<test/>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
xmlDoc2 = parser.parseFromString(text2,"text/xml");

var newElement=xmlDoc2.createElement("hello");

xmlDoc.getElementsByTagName("bookstore")[0].appendChild(newElement);
var oSerializer = new XMLSerializer();
var sXML = oSerializer.serializeToString(xmlDoc);
console.log(sXML);

I can't find why I need to use the same doc to create the element

Mohammad Karmi
  • 1,403
  • 3
  • 26
  • 42
  • 4
    "in Javascript if you want to create an element , you need to create element then append to child " That is not true – SLaks Mar 19 '19 at 15:14
  • In addition to the comment above, the rest of the problem is a duplicate of this SO question: https://stackoverflow.com/questions/25543588/appending-child-element-from-other-document – remix23 Mar 19 '19 at 15:39
  • I dont get an exception , can you please explain why should I have the same document ? – Mohammad Karmi Mar 19 '19 at 15:47

1 Answers1

1

You don't need to append an element to the same document that was used to create it.

createElement() creates an element owned by the document from which it is created but does not give it any position in the document. You can certainly create an element without appending it if you want to. appendChild() is one way to give an element a position in the document.

If you are working with multiple documents (as in your code example), you could create an element owned by one document and append it to a different document which would simply remove it from the original document owner, make the other document it's owner, and give it a position in the other document.

For example:

const astring = '<adoc></adoc>';
const bstring = '<bdoc></bdoc>';
const parser = new DOMParser();
const axml = parser.parseFromString(astring, 'application/xml');
const bxml = parser.parseFromString(bstring, 'application/xml');
const elem = axml.createElement('elem');
console.log(elem.ownerDocument.documentElement.tagName);
// adoc

bxml.querySelector('bdoc').appendChild(elem);
console.log(elem.ownerDocument.documentElement.tagName);
// bdoc
benvc
  • 14,448
  • 4
  • 33
  • 54