2

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.

Community
  • 1
  • 1
mikemaccana
  • 110,530
  • 99
  • 389
  • 494

1 Answers1

2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    "If you want an actual document that has html and body parts, then create a document, not a fragment." - can you elaborate? What's the most standard way to create an in-memory document I can use QuerySelectorAll and otherwise manipulate? I had some JQuery to do this earlier, but I'd like to use what's built into the browser. – mikemaccana May 27 '12 at 21:24
  • 1
    @nailer I think [this answer](http://stackoverflow.com/a/9319353/575527) has related resources to your question. – Joseph May 27 '12 at 21:29
  • 1
    @nailer - you don't need a document fragment in order to be able to use querySelector operations. Just create a div and assign your HTML to it and use querySelector operations on the div. No need for a document fragment at all. – jfriend00 May 28 '12 at 06:48
  • @nailer - your last comment was cut off. – jfriend00 Jun 02 '12 at 16:55