[webkit-dev] appendChild does not work for elements produced by DOMParser

Maciej Stachowiak mjs at apple.com
Mon Nov 30 04:58:50 PST 2009


On Nov 30, 2009, at 3:17 AM, Alexander Shabanov wrote:

> Hi all,
>
> Sorry for silly question but I think that it might be a nice feature  
> to webkit.
> The following code works in Mozilla Firefox 3.5, but it does not work
> in webkit-based browsers:
>
>       var parser = new DOMParser();
>       var str = "<p>This is a test</p>";
>       var doc = parser.parseFromString(str, "text/xml");
>       document.body.appendChild(doc.documentElement.firstChild);

If you change the last step to this, it will work in WebKit-based  
browsers:

document 
.body.appendChild(document.importNode(doc.documentElement.firstChild));

The Gecko engine is more generous about allowing implicit cross- 
document adoption. We allow it in only a few cases, and in theory it  
is not supposed to be allowed at all (without the importNode call)  
according to the DOM Core spec. That being said, if this is a compat  
issue on real sites we can change to be more Gecko-like.

>
> I found that specification to DOMParser does not guarantee that the
> result of DOMParser's parseFromX methods can
> be directly used in the original document.
> Nevertheless I believe that it would be quite a useful feature, at
> least it won't require JS code to create DOM-compliant content from
> the parsed one.
> May be I missed something and webkit offers a way of quick adaptation
> of the parsed content to the original DOM tree?
> Thanks in advance.
>
> P.S.: even though Firefox provides such a feature, a style
> specification in the following code will take no effect:
>       var parser = new DOMParser();
>       var str = "<p style='color: red;'>This is a test</p>";
>       var doc = parser.parseFromString(str, "text/xml");
>       document.body.appendChild(doc.documentElement.firstChild);

Probably because parsing with DOMParser parses as XML, thus you get a  
<p> element that's not an HTML element (it is in the null namespace  
instead of the HTML namespace). To get an HTML p element you need to  
either do this:

       var str = "<p xmlns='http://www.w3.org/1999/xhtml/'  
style='color: red;'>This is a test</p>";

or just use innerHTML or createContextualFragment to directly insert  
HTML text into a document.

Regards,
Maciej



More information about the webkit-dev mailing list