Reputation: 639
I have the following string :
var str = ‘<script type="text/javascript" src="js/test.js"></script><link rel="stylesheet" type="text/css" href="css/style.css" />’
How can I to transform this to DOM. I have tried with DOMParser something like this.
var parser = new DOMParser()
var el = parser.parseFromString(str, "text/xml");
console.log(el)
But, getting error. This is the output.
#document
<script type="text/javascript" src="file.js">
<parsererror style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
<h3>This page contains the following errors:</h3>
<div style="font-family:monospace;font-size:12px">error on line 1 at column 27: Extra content at the end of the document
</div>
<h3>Below is a rendering of the page up to the first error.</h3>
</parsererror>
</script>
As showing the output, the css has not been parsed too.
Upvotes: 0
Views: 919
Reputation: 6684
It seems DOMParser
can only parse a single element.
So this works:
new DOMParser().parseFromString("<div/>", "text/xml")
but this doesn't:
new DOMParser().parseFromString("<div/><div/>", "text/xml")
So you could probably fix your example by putting a tag around the whole thing.
Upvotes: 1