5.创建和操作节点
(1)创建新节点,一张IE(6.0)和FF对DOM Level1的创建新节点方法支持的对照表:
- 方法 IE FF
- createAttribute(name) Y Y
- createCDATASection(text) N Y
- createComment(text) Y Y
- createDocumentFragment() Y Y
- createElement(tagName) Y Y
- createEntityReference(name) N Y
- createProcessingInstruction(
- target,data) N Y
- createTextNode(text) Y Y
(2)createElement(),createTextNode(),appendChild()
广州网站建设,网站建设,广州网页设计,广州网站设计
- 例子:
- <html>
- <head>
- <title>createElement() Example</title>
- <script type="text/JavaScript">
- function createMessage() {
- var oP = document.createElement("p");
- var oText = document.createTextNode("Hello World!");
- oP.appendChild(oText);
- document.body.appendChild(oP);
- }
- </script>
- </head>
- <body onload="createMessage()">
- </body>
- </html>
在页面载入后,创建节点oP,并创建一个文本节点oText,oText通过appendChild方法附加在oP节点上,为了实际显示出来,将oP节点通过appendChild方法附加在body节点上。此例子将显示Hello World!
(3)removeChild(),replaceChild()和insertBefore()
从方法名称就知道是干什么的:删除节点,替换节点,插入节点。需要注意的是replaceChild和insertBefore两个参数都是新节点在前,旧节点在后。
(4)createDocumentFragment()
此方法主要是为了解决大量添加节点时,速度过慢。通过创建一个文档碎片节点,将要添加的新节点附加在此碎片节点上,然后再将文档碎片节点append到body上面,替代多次append到body节点。
广州网站建设,网站建设,广州网页设计,广州网站设计
- <html>
- <head>
- <title>insertBefore() Example</title>
- <script type="text/JavaScript">
- function addMessages() {
- var arrText = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"];
- var oFragment = document.createDocumentFragment();
- for (var i=0; i < arrText.length; i++) {
- var oP = document.createElement("p");
- var oText = document.createTextNode(arrText[i]);
- oP.appendChild(oText);
- oFragment.appendChild(oP);
- }
- document.body.appendChild(oFragment);
- }
- </script>
- </head>
- <body onload="addMessages()">
- </body>
- </html>
HTML DOM的特征功能
HTML DOM的特性和方法不是标准的DOM实现,是专门针对HTML同时也让一些DOM操作变的更加简便。
1.让特性像属性一样
访问某元素的特性需要用到getAttribute(name)方法,HTML DOM扩展,可以直接使用同样名称的属性来获取和设置这些值,比如:
- <img src="test.jpg"/>
2.table的系列方法:
为了简化创建表格,HTML DOM提供了一系列的表格方法,常用几个:
◆cells ——返回</tr>元素中的所有单元格
◆rows ——表格中所有行的集合
◆insertRow(position) ——在rows集合中指定位置插入新行
◆deleteRow(position) ——与insertRow相反
◆insertCell(position) ——在cells集合的指定位置插入一个新的单元格
◆deleteCell(position) ——与insertCell相反
遍历DOM
DOM的遍历是DOM Level2中提出的标准,IE6没有实现,Mozilla和Safari已经实现,最新IE7不清楚是否实现。