Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Bulk Insertion Using Document Fragment

The DocumentFragment node is a very lightweight version of the Element object meant for DOM cut and paste operations. A DocumentFragment node is a generic container for other nodes that can be inserted as a group somewhere else in the hierarchy. The DocumentFragment node must implement the DocumentFragment interface, which is a marker interface that extends Node but adds no new methods. The key to the DocumentFragment node type is how other methods treat it when it is passed as a parameter. Consider the following Java code:

import org.w3c.dom.*;
void dupEm(Document doc) {
  DocumentFragment frag = doc.createDocumentFragment();
  NodeList authors = doc.getElementsByTagNameNS("urn:bru",
  doc.getDocumentElement().appendChild (frag);

When frag is passed to appendChild, the implementation knows to "skip" the node being passed as an argument and instead enumerates its child nodes, appending each of them in turn. The following pseudocode shows how this is done:

void appendChild(Node node) {
  if (node.getNodeType() != Node.DOCUMENT_FRAGMENT_NODE)
  else {
    for (Node child = node.getFirstChild(); child != null;
         child = child.getNextSibling()) {

Note that due to this special treatment, DocumentFragment nodes never appear in a document's parent/children hierarchy.

  • + Share This
  • 🔖 Save To Your Account