美文网首页
obj.children.length和obj.childNod

obj.children.length和obj.childNod

作者: 别别扭扭的王姑娘 | 来源:发表于2017-02-14 13:54 被阅读0次

在学习获取父级的子级长度时,我们遇到了childNodes,接下来我们分析一下:children和childNodes:
children是父级的子级;childNodes是节点。
节点的常用属性有:nodeType、nodeName和nodeValue。
childNodes可分为元素节点、属性节点、文本节点。 我们获取到的obj.children.length仅仅是元素节点的个数。
总结:元素节点的nodeType为1,nodeName为标签名称,nodeValue是null;
属性节点的nodeType为2,nodeName为属性名称,nodeValue是属性值;
文本节点的nodeType为3,nodeName为#text,nodeValue是文本节点内容。
具体区别方式如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }   
        li{
            list-style:none;
        }   
    </style>
    <script>
        window.onload=function(){       
            var oUl=document.getElementById("ul");
            //获取到oUl子级的长度
            //alert(oUl.children.length);//5
            //获取到oUl子级节点的长度
            alert(oUl.childNodes.length);//11
            //获取到所有的childNodes
            var child=oUl.childNodes;
            //分别来存元素节点、属性节点、文本节点
            var arrElements=[],arrAttributes=[],arrTexts=[];
            for(var i=0; i<child.length; i++){
                //元素节点.nodeType===1
                if(child[i].nodeType===1){
                    arrElements.push(child[i]);
                }
                //属性节点.nodeType===2
                if(child[i].nodeType===2){
                    arrAttributes.push(child[i]);
                }
                //文本节点.nodeType===3
                if(child[i].nodeType===3){
                    arrTexts.push(child[i]);
                }
            }
            document.write('元素节点的个数是:'+arrElements.length+'<br/>');
            document.write('属性节点的个数是:'+arrAttributes.length+'<br/>');
            document.write('文本节点的个数是:'+arrTexts.length+'<br/>');
        };
    </script>
</head>
<body>
    <ul id="ul">
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</body>
</html>
   对于文本节点来说,它包括换行(空白符)、回车等。有的考虑到浏览器的兼容问题,要去除空白符文本节点,则需要在文本节点的判断条件上加上&&/\S/.test(child[i].nodeValue)如果不是空白符则添加,反之则不添加。
   根据之上的代码,我们就能区分children和childNodes的区别和联系了。

相关文章

网友评论

      本文标题:obj.children.length和obj.childNod

      本文链接:https://www.haomeiwen.com/subject/aspxwttx.html