Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DOMParser not preserving inline styles of parsed DOM?

I am simply trying to parse and append a JavaScript string as a DOM element. I have found two quick ways to do this, one of which is using DOMParser as seen in this popular SO answer. Both methods work, however, the DOMParser approach for some reason is not respecting the inline styles I define - even though both methods inject the exact same dynamic markup. Consider the following...

<div></div>

var parent = document.getElementsByTagName('div')[0]

// ---- case 1 ---------------

var parser = new DOMParser();
var node = parser.parseFromString('<p style="color: red">foo</p>', 'text/xml').firstChild;
parent.appendChild(node);

// ---- case 2 ---------------

var wrapper= document.createElement('div');
wrapper.innerHTML= '<p style="color: red">foo</p>';
var node2 = wrapper.firstChild;
parent.appendChild(node2);

Each method injects the node accordingly and the DOM reflects the following...

<div>
    <p style="color: red">foo</p>
    <p style="color: red">foo</p>
</div>

However, only the last is red! Any idea what can possibly be going on here?


JSFiddle - reproduction demo

like image 756
scniro Avatar asked Jul 12 '16 17:07

scniro


People also ask

What does the DOMParser object do?

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document . You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.

What is parsing in DOM?

A DOM Parser creates an internal structure in memory which is a DOM document object and the client applications get information of the original XML document by invoking methods on this document object. DOM Parser has a tree based structure.


1 Answers

That's because you didn't set a namespace. style attributes don't have any special meaning in XML:

var str = '<p xmlns="http://www.w3.org/1999/xhtml" style="color: red">foo</p>';
var node = new DOMParser().parseFromString(str, 'text/xml').firstChild;
document.body.appendChild(node);
like image 57
Oriol Avatar answered Oct 06 '22 02:10

Oriol