Reputation: 5847
I am using node
and xmldom
. On ocasion I parse XML from a string with the intention of adding it as a child to another element. However, I am confused by the following code:
var dom = require('xmldom').DOMParser;
var s = require('xmldom').DOMSerializer;
var childToBe = new dom().parseFromString('<div id="foo">Text</div>');
var parent = nodeWhereIWantToInsertChild();
parent.appendChild(childToBe);
This works just fine, and when I serialize it, I get what I expected
<parent><div id="foo">Text</div></parent>
Therefore, since div
is the child of parent
,
parent.childNodes[0].nodeName == 'div' // is true as expected.
Then why is
childToBe.nodeName == '#document' // ->True ????
childToBe.getAttribute('id') // ->Error, no method 'getAttribute'
If childToBe
is a #document and I appended it to parent
, why doesn't parent have a #document child?
Thanks!!
Upvotes: 0
Views: 279
Reputation: 161447
parseFromString
returns a Document
instance, not an Element
instance. Your appendChild
call should probably be throwing an exception since Document
is not allowed as a child of Element
, but the Node parser implementation probably doesn't bother checking.
What you probably want is to get the root element of the document:
var doc = new dom().parseFromString('<div id="foo">Text</div>');
var childToBe = doc.documentElement;
Upvotes: 1