js中的節點遍歷+類數組對象

firstChild  第一個子元素html

lastChild  最後一個子元素node

childNodes[n]  =   childNodes.item(n)    第n+1個子元素數組

parentNode  父元素瀏覽器

nextSibling  下一個兄弟元素app

previousSibling  上一個兄弟元素url

document.documentElement 獲取文檔的根節點spa

.tagName 標籤名prototype

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            var oHtml=document.documentElement;
            console.log(oHtml);

            var oHead=oHtml.firstChild;//獲取html的第一個子元素節點
            var oHead=oHtml.childNodes[0];
            var oHead=oHtml.childNodes.item(0);
            console.log(oHead);

            var oBody=oHtml.childNodes[1];
            console.log(oBody);
        });
    </script>
</head>
<body>    

</body>
</html>

 

 

 會返回head與body之間的空白文本節點(除了IE8如下的瀏覽器會忽略這個空白文本節點)code

任何節點均可以經過 .ownerDocument 得到根元素節點orm

.hasChildNodes() 判斷元素是否含有子節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            var oHtml=document.documentElement;
            console.log(oHtml);//獲取根元素節點

            var oHead=oHtml.firstChild;//獲取html的第一個子元素節點
            var oHead=oHtml.childNodes[0];
            var oHead=oHtml.childNodes.item(0);
            console.log(oHead);

            var oBody=oHtml.childNodes[1];
            console.log(oBody);

            console.log(oHead.parentNode==oHtml);//true
            console.log(oBody.parentNode==oHtml);//true

            console.log(oHead.nextSibling==oBody);//true
            console.log(oBody.previousSibling==oHead);//true

            console.log(box.ownerDocument);
            console.log(oHtml);
            console.log(box.ownerDocument==document);//true
            console.log(box.ownerDocument==oHtml);//false
            console.log(box.ownerDocument==oHtml.parentNode);//true 文檔的根元素節點的父元素節點=文檔節點

            console.log(box.hasChildNodes());//true
            console.log(box.childNodes[0].hasChildNodes());//false

        });

    </script>
</head>
<body>    
    <div id="box">這是box</div>
</body>
</html>

HTML結構樹打印

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var s="";
            function travelNode(space,node){
                // 若是不是空白節點
                if(node.tagName){
                    s+=space+node.tagName+"<br>";
                }
                var len=node.childNodes.length;//獲取該元素的子元素長度
                for(var i=0;i<len;i++){
                    travelNode(space+"|-",node.childNodes[i]);
                }
                
            }
            travelNode("",document);
            document.write(s);

        });

    </script>
</head>
<body>    
    <div id="box">
        <ul>
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

 

 

 只獲取元素節點,而過濾空白文本節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            for(var i=0,len=ul.childNodes.length;i<len;i++){
                if(ul.childNodes[i].nodeType==1){//判斷是不是元素節點
                    console.log(ul.childNodes[i]);
                }
            }

        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

 

 

 一組只獲取元素節點的API

 

 

 

firstElementChild 第一個元素子節點(直接子元素節點,而不是後代子元素節點)

lastElementChild 最後一個元素子節點(直接子元素節點,而不是後代子元素節點)

previousElementSibling  上一個兄弟元素

nextElementSibling 下一個兄弟元素

children[n] 第n+1個子元素節點

childElementCount 子元素節點數量

兼容性:IE9+

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            for(var i=0,len=ul.childElementCount;i<len;i++){
                console.log(ul.children[i]);
            }

        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

 

 

 NodeList 類數組對象

能夠經過[]來訪問,有item方法和length屬性

使用ele.childNodes便可獲取到nodeList

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            console.log(ul.childNodes);//NodeList(11) [text, li, text, li, text, li, text, li, text, li, text]
            console.log(ul.childNodes[1]);//<li>item1</li>
            console.log(ul.childNodes.item(1));//<li>item1</li>

        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

 

類數組對象不是數組

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            console.log(ul.childNodes);//NodeList(11) [text, li, text, li, text, li, text, li, text, li, text]
            ul.childNodes.push("<li>item6</li>");//Uncaught TypeError: ul.childNodes.push is not a function at HTMLDocument.<anonymous>

        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

接下來將類數組對象轉爲數組

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            console.log(ul.childNodes);//NodeList(11) [text, li, text, li, text, li, text, li, text, li, text]
            //ul.childNodes.push("<li>item6</li>");//Uncaught TypeError: ul.childNodes.push is not a function at HTMLDocument.<anonymous>

            function toArray(nodeList){    
                var arr=null;
                arr=new Array();
                for(var i=0,len=nodeList.length;i<len;i++){
                    arr.push(nodeList[i]);
                }
                return arr;
            }

            var newNodeList=toArray(ul.childNodes);
            newNodeList.push("<li>item6</li>");
            console.log(newNodeList);//(12) [text, li, text, li, text, li, text, li, text, li, text, "<li>item6</li>"]
        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

 

Array.prototype.slice.call() 能夠將類數組對象轉爲數組,可是在低版本IE中會報錯

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            console.log(ul.childNodes);//NodeList(11) [text, li, text, li, text, li, text, li, text, li, text]
            //ul.childNodes.push("<li>item6</li>");//Uncaught TypeError: ul.childNodes.push is not a function at HTMLDocument.<anonymous>

            var newNodeList=Array.prototype.slice.call(ul.childNodes);            
            newNodeList.push("<li>item6</li>");
            console.log(newNodeList);//(12) [text, li, text, li, text, li, text, li, text, li, text, "<li>item6</li>"]
        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

下面是兼容低版本IE的寫法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ul=document.getElementById("ul");
            console.log(ul.childNodes);//NodeList(11) [text, li, text, li, text, li, text, li, text, li, text]
            //ul.childNodes.push("<li>item6</li>");//Uncaught TypeError: ul.childNodes.push is not a function at HTMLDocument.<anonymous>

            function toArray(nodeList){
                var arr=null;
                try{
                    var newNodeList=Array.prototype.slice.call(nodeList);
                    return newNodeList;
                }catch(e){
                    arr=new Array();
                    for(var i=0,len=nodeList.length;i<len;i++){
                        arr.push(nodeList[i]);
                    }
                    return arr;
                }
            }
            var newNodeList=toArray(ul.childNodes);
            newNodeList.push("<li>item6</li>");
            console.log(newNodeList);
        });

    </script>
</head>
<body>    
    <div id="box">
        <ul id="ul">
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
            <li>item4</li>
            <li>item5</li>
        </ul>
    </div>
</body>
</html>

 

 

 類數組對象HTMLCollection

ele.getElementsByTagName() 獲取全部該標籤的元素集合

document.scripts  scripts元素集合

document.links  全部的a標籤

document.images  image集合

document.forms  form表單集合

tr.cells  tr下的全部td集合

select.options  select下的全部option元素集合

HTMLCollection中有name  item  namedItem

.namedItem(value) 

首先嚐試返回有id=value的元素

若是沒有,就返回name=value的元素

注意只返回一個

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var ps=document.getElementsByTagName("p");
            var scripts=document.scripts;
            var links=document.links;
            var forms=document.forms;
            var images=document.images;
            var tds=document.getElementById("tr1").cells;
            var options=document.getElementById("select").options;

            console.log(ps);//HTMLCollection(2) [p, p]
            console.log(scripts);//HTMLCollection(2) [script, script]
            console.log(links);//HTMLCollection(2) [a, a]
            console.log(forms);//HTMLCollection(2) [form, form]
            console.log(images);//HTMLCollection(2) [img, img]
            console.log(tds);//HTMLCollection(4) [td, td, td, td]
            console.log(options);//HTMLOptionsCollection(3) [option, option, option, selectedIndex: 0]

            console.log(tds.namedItem("td"));//<td id="td">1</td>

        });

    </script>
</head>
<body>
    <p>這是p標籤1</p>
    <p>這是p標籤2</p>

    <a href="#">這是a連接1</a>
    <a href="#">這是a連接2</a>

    <form action="">
        <select name="select" id="select">
            <option value=""></option>
            <option value=""></option>
            <option value=""></option>
        </select>
    </form>
    <form action="">
    </form>

    <img src="source/cat-little.jpg" alt="">
    <img src="source/cat-little.jpg" alt="">

    <table>
        <tr id="tr1">
            <td id="td">1</td>
            <td name="td">2</td>
            <td name="td">3</td>
            <td>4</td>
        </tr>
    </table>
    

</body>
</html>

 

 

 類數組對象namedNodeMap

經過.attributes獲得

獲取元素的全部屬性,包括系統自帶屬性和自定義屬性

有item方法和length屬性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var list=document.getElementById("list");
            var attrs=list.attributes;

            console.log(attrs);//NamedNodeMap {0: id, 1: data-url, 2: data-action, id: id, data-url: data-url, data-action: data-action, length: 3}
            console.log(attrs.length);//3
            console.log(attrs[0]);//id="list"
            console.log(attrs.item(1));//data-url="index.html"

        });

    </script>
</head>
<body>
    <ul id="list" data-url="index.html" data-action="submit">
        <li></li>
        <li></li>
        <li></li>
    </ul>
</body>
</html>

 

類數組對象:nodeList   HTMLCollection   namedNodeMap

都具備動態性

每當文檔結構發生變化時,就會隨之更新

appendChild() 追加子元素

證實:嘗試獲取到最初div元素的個數,而且在頁面中追加同等個數的div(即數量加倍的效果)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var divs=document.getElementsByTagName("div");//HTMLCollection類數組對象
            var i=0;
            while(i<divs.length){
                document.body.appendChild(document.createElement("div"));
                i++;
            }

        });

    </script>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>

結果頁面崩潰

緣由是每次在循環時,會從新計算div元素的個數,致使div元素的個數永遠都在動態改變,致使while循環沒法結束

解決方法是將最初div元素的個數用一個變量保存起來

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body{
            width:100%;
            height:100%;
        }
    </style>
    <script src="DomReady.js"></script>
    <script>
        myReady(function(){
            
            var divs=document.getElementsByTagName("div");//HTMLCollection類數組對象
            var i=0;
            var length=divs.length;
            while(i<length){
                document.body.appendChild(document.createElement("div"));
                i++;
            }

        });

    </script>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>

相關文章
相關標籤/搜索