Search code examples
google-closure-library

Closure library dom node from html text


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?


Solution

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