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

一世执手 提交于 2019-11-30 05:07:31

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15245124/domparser-injects-dom-but-does-not-apply-css-stylesheets-once-injected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!