一、DOM节点

1.获取子节点:

childNodes 
nodeType         节点类型
children            只包括元素,不包括文本;  子节点只算第一层。只算孩子一级。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
window.onload=function ()
{
    var oUl=document.getElementById('ul1');
    
    //IE6-8
    //alert(oUl.childNodes.length);
    for(var i=0;i<oUl.childNodes.length;i++)
    {
        //nodeType==3    ->    文本节点
        //nodeType==1    ->    元素节点
        //alert(oUl.childNodes[i].nodeType);
        
        if(oUl.childNodes[i].nodeType==1)
        {
            oUl.childNodes[i].style.background='red';
        }
    }
};
</script>
</head>

<body>
<ul id="ul1">
    <li></li>
    <li></li>
</ul>

aaaa
bbbb

fafafsdfasd    文本节点
<span>qwerqwre 元素节点</span>

</body>
</html>
View Code

当获取ul1下面的childNodes时,chrome和FF下length都是5,因为把空的文本节点也算上了。

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
window.onload=function ()
{
    var oUl=document.getElementById('ul1');
    
    //alert(oUl.children.length);
    for(var i=0;i<oUl.children.length;i++)
    {
        oUl.children[i].style.background='red';
    }
};
</script>
</head>

<body>
<ul id="ul1">
    <li></li>
    <li></li>
</ul>

aaaa
bbbb

fafafsdfasd    文本节点
<span>qwerqwre 元素节点</span>

</body>
</html>
View Code

使用children获取到的length就是2了。

 

2.parentNode

例子:点击链接,隐藏整个li

相关文章: