第二课 html的组织结构以及发展方向

下面是一个遍历文档的例子,通过使用Dom将一个HTML文档解析成树状的结构!
在Dom眼中,HTML跟XML一样是一种树状结构的文档<html>是根root
<head><title><body>是html的childre节点,相互之间是兄弟sibling
<body>下面才是子节点<table><span><p>

例子1遍历HTML树
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Ch04--统计Element节点总数</title>
<script language="javascript">
var elementName = ""; //全局变量,保存Element标记名,使用完毕要清空
function countTotalElement(node) { //参数node是一个Node对象
var total = 0;
if(node.nodeType == 1) { //检查node是否为Element对象
total++; //如果是,计数器加1
elementName = elementName + node.tagName + "\r\n"; //保存标记名
}
var childrens = node.childNodes; //获取node的全部子节点
for(var i=0;i<childrens.length;i++) {
total += countTotalElement(childrens[i]); //在每个子节点上进行递归操作
}
return total;
}
</script>
</head>

<body>
<table width="100" border="1" cellpadding="0" cellspacing="0">
<tr><td>
<form name="form1" action="" method="post">
<input type="text" name="input1" value=""><br>
<input type="password" name="password1" value="">
</form>
</td></tr>
</table>
<a href="javascript:void(0)" onClick="alert('标记总数:' + countTotalElement(document) + '\r\n全部标记如下:\r\n' + elementName);elementName='';">开始统计</a>
</body>
</html>


案例2 通过DOM编程来灵活的生成页面内容
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Ch04--颠倒表格行顺序</title>
<script language="javascript">
function reverseTable() {
var node = document.getElementsByTagName("table")[0]; //第一个表格
var child = node.getElementsByTagName("tr"); //取得表格内的所有行
var newChild = new Array(); //定义缓存数组,保存行内容
for(var i=0;i<child.length;i++) {
newChild[i] = child[i].firstChild.innerHTML;
}
node.removeChild(node.childNodes[0]); //删除全部单元行
var header = node.createTHead(); //新建表格行头
for(var i=0;i<newChild.length;i++) {
var headerrow = header.insertRow(i); //插入一个单元行
var cell = headerrow.insertCell(0); //在单元行中插入一个单元格
//在单元格中创建TextNode节点
cell.appendChild(document.createTextNode(newChild[newChild.length-i-1]));
}
}
</script>
</head>
<body>
<table width="200" border="1" cellpadding="4" cellspacing="0">
<thead>
    <tr>
        <td height="25">第一行</td>
    </tr>
    <tr>
        <td height="25">第二行</td>
    </tr>
    <tr>
        <td height="25">第三行</td>
    </tr>
    <tr>
        <td height="25">第四行</td>
    </tr>
</thead>
</table>
<br>
<input type="button" name="reverse" value="开始颠倒" onClick="reverseTable()">
</body>
</html>

你可能感兴趣的:(html,编程,xml)