nodeType nodeName nodeValue实例测试

nodeType nodeName nodeValue实例测试

注意:nodeName总是返回一个大写字母的值,即使元素在Html文档里是小写字母。

 <!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>
</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>
<script type="text/javascript">
function showElement(){
var element = document.getElementById("h1");//h1是一个<h1>标签
console.log('nodetype:' + element.nodeType);//nodeType=1
console.log('nodeName:' + element.nodeName);
console.log(
'nodeValue:' + element.nodeValue); //null
console.log('element:' + element);
}

function showText(){
var element = document.getElementById("h1");
var text = element.childNodes[0];
console.log(
'nodeType:' + text.nodeType); //nodeType=3
console.log('nodeValue:' + text.nodeValue); //文本节点的nodeValue是其文本内容
text.nodeValue = text.nodeValue + "abc"; //文本内容添加修改删除等等。
console.log('nodeName:' + text.nodeName);
console.log(text.data);
//data同样是其内容,这个属性下同样可以增删改。
}

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

function showAttr(){
var btn = document.getElementById("btnShowAttr");//演示按钮,有很多属性
console.log(btn);
var attrs = btn.attributes;
console.log(attrs);
for (var i = 0; i < attrs.length; i++) {
console.log(attrs[i].nodeType);
//attribute 的nodeType=2
console.log(attrs[i].nodeName);
console.log(attrs[i].nodeValue);
console.log(attrs[i].name);
console.log(attrs[i].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;
</script>
</body>
</html>



posted @ 2011-09-21 16:17  wkylin  阅读(384)  评论(0编辑  收藏  举报