Search code examples
jquerydocumentfragment

JQuery just created empty div doesn't have document fragment as parent


When creating new html node in jQuery using

$('<some-node>some html code</some-node>');

it won't become part of DOM, until you attach it. However, it does not mean, the node has no parent.

If the node was created unempty, e.g.:

var myNewNode = $('<div>Hello</div>');

You can check the parent:

myNewNode[0].parentNode; // Who is the parent?

and see you get

DocumentFragment

as result. DocumentFragment is some object similar to document, however, not part of the DOM tree.

The strange thing comes now. When you create an empty node, like

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

and try to check its contents

myNewEmptyNode[0].parentNode; // Who is now the parent?

surprisingly you get

null

I cannot understand this behaviour and found nothing about it in jQuery documentation. I found it when trying to debug why javascriptMVC mxui modal was failing on an empty div.

I have tested this behaviour in both Chromium and Opera, so it does not seem to be a browser related issue.

Does someone have an explanation for this?


Solution

  • That's due to the fact that jQuery uses document.createElement for "quick" HTML strings, but jQuery.buildFragment for all other (more "complex") HTML strings. <div></div> is considered quick, whereas <div>a</div> is not.

    I set up a fiddle so you can check: http://jsfiddle.net/PzBSY/2/.

    "Quick" is defined with the regular expression:

    var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/;
    

    which passes the empty div string, but not the non-empty div string. Note the if/else block after the check which makes for the two branches.

    So it's basically because jQuery explicitly builds a document fragment with the non-empty div, whereas it does not with the empty div (it just uses document.createElement("div") instead).