Question

I would like to use DocumentFragment and querySelector to make and modify DocumentFragments. I am using some code from Inserting arbitrary HTML into a DocumentFragment to create the fragments from HTML strings:

stringToDocumentFragment = function(html_string) {
    var frag = document.createDocumentFragment();
    var holder = document.createElement("div")
    holder.innerHTML = html_string
    frag.appendChild(holder)
    return frag
}

And it works:

test_one = stringToDocumentFragment('<one><two>test</two></one>')
#document-fragment

test_one.querySelector('one')
> <one>...</one>

However, if I use elements like <html> or <body>, it fails:

test_two = stringToDocumentFragment('<html><body>test</body></html>')
#document-fragment

test_two.querySelector('html')
null

The behaviour is identical in both Chrome and Firefox.

Was it helpful?

Solution

A document fragment is meant to be a piece of a document, not an entire document - thus you should not have <body> and <html> in a document fragment. The point of a document fragment it to have a way to create or store a number of top level elements (a piece of some document). When inserted into an actual document, only the elements inside are inserted, not the top level container.

If you want an actual document that has html and body parts, then create a document, not a fragment.

If you just want to be able to use selector operations, then you don't need to use a fragement at all. Just create a div and set the innerHTML on a div and use querySelector operations on the div. You don't need a document fragment for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top