scniro scniro - 1 year ago 94
HTML Question

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 simple ways to do this, one of which is using DOMParser as seen in this popular SO answer. Both methods work, however, the DOMParser method for some reason is not preserving the styles - even though both methods inject the exact same dynamic markup. Consider the following...


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;

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

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

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

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

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

JSFiddle - reproduction demo

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download