HTML DOM的nodeType值

將HTML DOM中幾個容易常用的屬性做下記錄:
nodeName、nodeValue 以及 nodeType 包含有關於節點的信息。

nodeName 屬性含有某個節點的名稱。

* 元素節點的 nodeName 是標籤名稱
* 屬性節點的 nodeName 是屬性名稱
* 文本節點的 nodeName 永遠是 #text
* 文檔節點的 nodeName 永遠是 #document

註釋:nodeName 所包含的 XML 元素的標籤名稱永遠是大寫的
nodeValue

對於文本節點,nodeValue 屬性包含文本。

對於屬性節點,nodeValue 屬性包含屬性值。

nodeValue 屬性對於文檔節點和元素節點是不可用的。
nodeType

nodeType 屬性可返回節點的類型。

最重要的節點類型是:
[table]
|元素類型|節點類型|
|元素element|1|
|屬性attr|2|
|文本text|3|
|註釋comments|8|
|文檔document|9|
[/table]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DOM標準</title>
<script type="text/javascript" src="test.js"></js>
</head>
<body>
<h1 id="h1">An HTML Document</h1>
<p id="p1">This is a <i>W3C HTML DOM</i> document.</p>
<p><input id="btnDemo1" type="button" value="取H1 Element節點值"></p>
<p><input id="btnDemo2" type="button" value="取H1 Element節點文本"></p>
<p><input id="btnDemo3" type="button" value="取Document Element節點文本"></p>
<p><input type="button" alt="這是個演示按鈕" title="演示按鈕提示標題" name="btnShowAttr" id="btnShowAttr" value="按鈕節點演示" /></p>
</body>
</html>


function showElement(){
var element=document.getElementById("h1");//h1是一個<h1>標籤
alert('nodetype:'+element.nodeType);//nodeType=1
alert('nodeName:'+element.nodeName);
alert('nodeValue:'+element.nodeValue); //null
alert('element:'+element);
}

function showText(){
var element=document.getElementById("h1");
var text=element.childNodes[0];
alert('nodeType:'+text.nodeType); //nodeType=3
alert('nodeValue:'+text.nodeValue); //文本節點的nodeValue是其文本內容
text.nodeValue=text.nodeValue+"abc"; //文本內容添加修改刪除等等。
alert('nodeName:'+text.nodeName);
alert(text.data); //data同樣是其內容,這個屬性下同樣可以增刪改。
}

function showDocument(){
alert('nodeType:'+document.nodeType); //9
alert('nodeName:'+document.nodeName);
alert(document);
}

function showAttr(){
var btnShowAttr=document.getElementById("btnShowAttr"); //演示按鈕,有很多屬性
var attrs=btnShowAttr.attributes;
for(var i=0;i<attrs.length ;i++){
var attr=attrs[i];
alert('nodeType:'+attr.nodeType); //attribute 的nodeType=2
alert('attr:'+attr);
alert('attr.name:'+attr.name+'='+attr.value);

}

}

function demo(){
var btnDemo1=document.getElementById("btnDemo1");
btnDemo1.onclick=showElement; //按鈕1取節點nodetype值
var btnDemo2=document.getElementById("btnDemo2");
btnDemo2.onclick=showText;
var btnDemo3=document.getElementById("btnDemo3");
btnDemo3.onclick=showDocument;
var btnShowAttr=document.getElementById("btnShowAttr");
btnShowAttr.onclick=showAttr;

}
window.onload=demo;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章