DocumentFragment (W3C DOM Core object)

Spec
Version Depr. Parent
DOM1 No Node
Browser support (more…)
IE5.5+ FF1.5+ SA1.3+ OP9+
Partial Full Full Full

Example

var fragment = document.createDocumentFragment();

var heading = fragment.appendChild(document.createElement('h1'));
heading.appendChild(document.createTextNode('Quotes by Yoda'));
var blockquote = fragment.appendChild(document.createElement('blockquote'));
var p = blockquote.appendChild(document.createElement('p'));
p.appendChild(document.createTextNode('Always two there are'));

document.getElementsByTagName('body').item(0).appendChild(fragment);

The example above creates a document fragment, adds some HTML to it, then appends the entire sub-tree to the <body> of the main document.

So, if the original HTML looked like this:

<body>
</body>

The operation above would result in this1:

<body>
  <h1>Quotes by Yoda</h1>
  <blockquote>
    <p>Always two there are</p>
  </blockquote>
</body>

Description

The DocumentFragment interface inherits from Node, and is a lightweight version of the Document interface, intended for temporary storage of DOM structures. For example, it can be used as a temporary canvas for building a group of nodes, or to store a group of nodes while moving it from one part of a document to another.

Many node manipulation methods can take a document fragment as their argument (for example, appendChild), and this results in the fragment's entire sub-tree being appended, but not the DocumentFragment itself — a document fragment is a virtual construct, and never actually appears in a document.

A DocumentFragment node can have Element, ProcessingInstruction, Comment, Text, CDATASection and EntityReference nodes as children.

Compatibility

Internet Explorer Firefox Safari Opera
5.5 6.0 7.0 1.5 2.0 3.0 1.3 2.0 3.0 9.0 9.5
Partial Partial Partial Full Full Full Full Full Full Full Full

Internet Explorer 5.5 in HTML doesn't implement this interface.

Internet Explorer 6 and 7 don't inherit the normalize method from Node.

Note: Viewlink content is not a Document Fragment

Viewlink content in Internet Explorer2 is referred to as a "document fragment" in the MSDN documentation, but it actually isn't a DocumentFragment, it's a Document.

CAUTION: Cross-document manipulation of document fragments

The ability to append nodes to a document fragment which were created in a different document varies by browser, from working fine at one end, to crashing at the other. For details please see appendChild.

Footnotes

1 Except the whitespace wouldn't really be there — that's just to make the example more readable.

2 Viewlink is a feature of DHTML Behaviors, a proprietary technology in Internet Explorer, which attaches scripted behaviors to elements via CSS-like selectors.

User-contributed notes

There are no comments yet.

Related Products