JavaScript HTML DOM节点类型之DocumentFragment类型


DocumentFragment(文档片断)是一种轻量级的文档,DocumentFragment是唯一一种在文档中没有文档标记的类型,它可以包含和控制节点,便不会像完整文档那样占用额外的资源。


  1. DocumentFragment类型
  2. DocumentFragment类型介绍

1. DocumentFragment类型

创建一个DocumentFragment类型的节点可以使用以下两种方法:

// 使用Document对象创建
var dfragment1 = document.createDocumentFragment();

// 使用构造函数创建
var dfragment2 = new DocumentFragment();

一个DocumentFragment类型的节点具有以下特征:

  • nodeType值为11
  • nodeName值为"#document-fragment"
  • nodeValue值为null
  • parentNode值为null
  • 子节点可以是:Element、Comment、Text、ProcessingInstruction、CDATASection、EntityReference

不能直接把DocumentFragment类型添加到文档中,但可以将它做来一个仓库,用来存储可能会被添加到文档中的节点。


2. DocumentFragment类型介绍

DocumentFragment对象继承自NodeNode对象中所有的方法和属性都可以DocumentFragment中使用,但DocumentFragment对象通常用于执行那些针对DOM的操作。

在浏览器所使用的一般是htmlxhtml类型的文档,所以entitiesnotations属性都是一个空列表。

如,向以下ul列表表中插入子节点:

<ul id="myUl"></ul>

代码如下:

var dfragment = document.createDocumentFragment();
var ul = document.getElementById('myUl');
var li = null;

for(var i=0; i<3; i++){
  li = document.createElement('li');
  li.appendChild(document.createTextNode('列表项:'+i));
  dfragment.appendChild(li);
}
ul.appendChild(dfragment);