Search code examples
javascripthtmldocumentfragment

Can I convert an HTML comment to actual HTML using JavaScript?


If I insert a comment node into a document fragment, can I convert it to HTML later? Example:

var fragment = document.createDocumentFragment();
var comment = document.createComment('<div>Testing</div>');

fragment.appendChild(comment);

// Convert comment into actual HTML?

What this would look like inside of a fragment:

<!--<div>Testing</div>-->

And how it should be when done (actual DOM):

<div>Testing</div>

Background:

There are many limitations for inserting HTML into a fragment. Fragments don't support innerHTML or insertAdjacentHTML etc. There are other methods for getting HTML into fragments, but they drop certain elements and leave only the inner text. For example, creating a fragment with the createRange API drops those types of nodes and I will be left with a fragment with just the text node "Data"

var fragment = document.createRange().createContextualFragment('<td>Data</td>');

The hope is that if I can convert a comment into actual DOM, that it will work as expected.


Solution

  • It sounds like your underlying problem is that you need to stuff HTML text into a DocumentFragment, so here is a helper function to do so for you.

    var container = document.createElement('div')
    
    function createFragmentWithHTML (html, doc) {
      var result = (doc || document).createDocumentFragment()
      container.innerHTML = html
      while (container.firstChild) result.appendChild(container.firstChild)
      return result
    }
    
    
    var fragment = createFragmentWithHTML('<div>Testing</div><p><strong>More text</strong></p>')
    
    // do whatever you want with `fragment`
    document.body.appendChild(fragment)