DOM中元素节点、属性节点、文本节点

DOM中有12中节点,但最常用到的是元素节点,属性节点,文本节点。

元素节点的节点类型(nodeType)是1;

属性节点的节点类型(nodeType)是2;

文本节点的节点类型(nodeType)是3。

元素节点的 nodeName 是标签名称
属性节点的 nodeName 是属性名称
文本节点的 nodeName 永远是 #text

对于文本节点,nodeValue 属性包含文本。

对于属性节点,nodeValue 属性包含属性值。

nodeValue 属性对于文档节点和元素节点是不可用的。

nodeValue就是用来得到“文本元素的值”的,即只适用于“文本节点”;

看下例子

<html>
<head>
<script type="text/javascript">
function getNodeValue()
{
var nv=document.getElementById("td1").firstChild.nodeValue;
var nn=document.getElementById("tr1").nodeValue;
var nv1=document.getElementById("tr1").firstChild.nodeValue;
console.log("nv="+nv);//nv=Silence
console.log("nn="+nn);//nn=null
console.log("nv1="+nv1);//nv1=
console.log(document.getElementById("tr1").firstChild);//<TextNode textContent="
 ">
console.log(document.getElementById("td1").firstChild);//<TextNode textContent="Silence">
}
</script>
</head>
<body>
<table>
  <tr id="tr1">
    <td id="td1" >Silence</td>
    <td>bean</td>
    <td>happy</td>
  </tr>
</table>
<input type="button" value="按钮"  onclick="getNodeValue()"/>
</body>
</html>

 

原文地址:https://www.cnblogs.com/MissBean/p/4309371.html