我有一个像这样的html文本:
'<div class="a"><span>1</span><div>2</div></div>'
闭包库中是否有一个函数可以获取这样的字符串作为输入并返回 DOM 树以插入到文档中?
我有一个像这样的html文本:
'<div class="a"><span>1</span><div>2</div></div>'
闭包库中是否有一个函数可以获取这样的字符串作为输入并返回 DOM 树以插入到文档中?
闭包库提供了从对象goog.dom.safeHtmlToNode(html)
创建文档片段 ( Node
)的功能goog.html.SafeHtml
,可以使用goog.html.sanitizer.HtmlSanitizer
如下所示创建。
<!doctype html>
<html>
<head>
<title>Closure Library Dom Test</title>
<script src="https://cdn.rawgit.com/google/closure-library/master/closure/goog/base.js"></script>
<script>
goog.require('goog.dom');
goog.require('goog.html.SafeHtml');
goog.require('goog.html.sanitizer.HtmlSanitizer');
</script>
</head>
<body>
<h1>Closure Library Dom Test</h1>
<div id="main">
</div>
<script>
var sanitizer = new goog.html.sanitizer.HtmlSanitizer.Builder().build();
var fragment = goog.dom.safeHtmlToNode(
sanitizer.sanitize('<div class="a"><span>1</span><div>2</div></div>'));
goog.dom.append(/** @type {!Node} */(document.querySelector('#main')),
/** @type {!Node} */(fragment));
</script>
</body>
</html>