duck degen
duck degen

Reputation: 1223

DOMParser injects DOM but does not apply css stylesheets once injected?

I have a little testcase over at:

http://jsfiddle.net/9xwUx/1/

The code boils down to the following (given a node with id "target"):

var string = '<div class="makeitpink">this should be pink, but is not</div>';
var parser = new DOMParser();
var domNode = parser.parseFromString(string,"text/xml");
document.getElementById("target").appendChild(domNode.firstChild);

If you run the testcase, and then inspect the target node via firebug/chrome web inspector and select any node within the body tag of jsfiddle's iframe, and do "edit as HTML", add a random charachter anywhere as a string [not an attribute to a domnode, to be clear], and "save", the style is applied. but not before that. To say that i'm confused is an understatement.

Can anybody please clarify what is going on here? Thanks.

Upvotes: 7

Views: 2816

Answers (2)

ngryman
ngryman

Reputation: 7672

You can change the mime type to text/html and do the following:

var parser = new DOMParser()
var doc = parser.parseFromString(markup, 'text/html')
return doc.body.firstChild

I didn't test on every browser but it works on Chrome and Firefox. I don't see any reason it wouldn't work elsewhere.

Upvotes: 6

kieran
kieran

Reputation: 1537

a bit late, but the reason is that you have parsed these using the text/xml option, which means that the results are XML nodes, which don't have CSS applied to them. When you right-click and go "edit as HTML" the browser reinterprets them as HTML and the change in the element will cause a redraw, reapplying the CSS.

I've been parsing my using the relatively hack-ish, yet definitely working method of creating a temporary element and manipulating the innerHTML property, making the browser do the parsing instead:

var temp = document.createElement("div")
//assuming you have some HTML partial called 'fragment'
temp.innerHTML = fragment
return temp.firstChild

Which you've noted in your jsfiddle. Basically it boils down to the output of the DOMParser being an instance of XMLDocument when you use the text/xml option.

Upvotes: 1

Related Questions