Closure library dom node from html text

懵懂的女人 提交于 2019-12-04 03:56:55

问题


I have an html text like:

'<div class="a"><span>1</span><div>2</div></div>'

Is there a function in closure library to get such a string as input and return a DOM tree to insert in a document?


回答1:


Closure Library provides the function goog.dom.safeHtmlToNode(html) to create a document fragment (Node) from a goog.html.SafeHtml object, which can be created using goog.html.sanitizer.HtmlSanitizer as shown below.

Example

<!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>


来源:https://stackoverflow.com/questions/12318667/closure-library-dom-node-from-html-text

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