简体   繁体   English

将字符串解析为DOM

[英]parse string to DOM

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. 如何将其转换为DOM。 I have tried with DOMParser something like this. 我已经尝试使用DOMParser这样的东西。

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. 如图所示,css也没有被解析。

It seems DOMParser can only parse a single element. 似乎DOMParser只能解析单个元素。

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. 因此,您可以通过在整个标签周围放置标签来修正示例。

Your single quotes are wrong? 您的单引号有误吗? Please double check. 请仔细检查。

I think you can use jQuery or Mootools to transfer easily: 我认为您可以使用jQueryMootools轻松进行传输:

var s = '<script type="text/javascript" src="js/test.js"></script><link rel="stylesheet" type="text/css" href="css/style.css" />';
var v = $(s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM