3

Is creating a DocumentFragment, the same as creating a $('<div/>')?

E.g.:

var fragment = $(document.createDocumentFragment());

vs

var detached = $('<div/>');

I'm unsure about the advantages of using a DocumentFragment like that when detached elements seem very similar.

Akshay Rawat
  • 4,714
  • 5
  • 40
  • 65
  • 2
    a `fragment` is not an html element like a `div`, it can contain html elements but it has no representation in the DOM. [doc](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment). It's usefull when you create a list of elements without add them directly to the DOM (no redraw on each DOM modifications) – Hacketo Mar 06 '15 at 10:26
  • 1
    jQuery will not create a document fragment if you build a single element (as in your `$("
    ")` example. It will use `document.createElement()` instead.
    – Frédéric Hamidi Mar 06 '15 at 10:28
  • Does wrapping it in `$` do a `document.createElement()` ? `$(document.createDocumentFragment());`, or is it still detached from DOM? – Akshay Rawat Mar 06 '15 at 10:35
  • 1
    @AkshayRawat No, it's just a jQuery object that contains your fragment – Hacketo Mar 06 '15 at 10:37
  • When you append a `documentFragment` to the dom, you only add it's content to the dom, not like adding a `div`. If the fragment contains nothing, it add nothing to the dom. – Hacketo Mar 06 '15 at 10:46

0 Answers0