DOM节点:
childNodes nodeType
childNodes有兼容性问题,在FF、Chrome、IE9+下会计算文本节点。(例:如下代码)
<!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" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <script> window.onload=function(){ var oUl = document.getElementById('ul1'); alert(oUl.childNodes.length);
/* childNodes 结合 nodeType 使用 */
for(var i=0;i<oUl.childNodes.length;i++){
if(oUl.childNodes[i].nodeType == 1){ //判断是否为标签节点 文本节点nodeType值为3
oUl.childNodes[i].style.background='red';
}
}
} </script> </head> <body> <ul id="ul1"> <li>001</li> <li>002</li> <li>003</li> </ul> </body> </html>
在IE8及以下的浏览器得到结果为: 3
IE9+/FF/chrome得到结果为: 7
-获取子节点
children :功能跟childNodes一样,区别是不会将文本节点计算在内。所以可以理解为childNodes的兼容版。
parentNode:获取到的是结构上的父级。
offsetParent:获取到的是物体相对定位的父级。