JS中Node節點總結


Node的三個基本屬性:

  1.nodeType:表明節點類型,1是元素節點,3是文本節點。

  2.nodeName:  表明節點名稱,元素節點為標簽名,文本節點為#text。

  3.nodeValue:表明節點值,元素節點為null,文本節點為文本內容。

Node的節點關系:

  1.parentNode與childNodes

    parentNode尋找當前節點的父節點,childNodes尋找當前節點的子節點,其中包括文本節點和元素節點(特別需要注意空白的文本節點也算是節點)如下程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>childNodes.length</title>
</head>
<body>
    <ul id="ul">
        <li></li>
        <li></li>
        <li></li>
    </ul>
    <script>
        var oUl=document.getElementById('ul');
        alert(oUl.childNodes.length);//是7不是3
    </script>
</body>
</html>

  2:firstChild與lastChild

    分別對應父節點的第一個節點與最后一個節點,firstChild相當於childNodes[0]或childNodes.item(0)。

  3.nextSibling與previousSibling

    分別對應當前節點的前一個節點與當前元素的后一個節點。

Node的操作節點:

  Node的操作節點有appendChild(),insertBefore(),replaceChild(),removeChild(),cloneNode(),normalize()

  1.appendChild(newNode)是將newNode添加到當前節點的最后一個子節點的后面,如果newNode已經是文檔的一部分,則appendChild操作相當於剪切;若果newNode是新創造的節點,則appendChild操作相當於添加。

  2.insertBefore(newNode,oldNode)是將newNode添加到當前節點的oldNode子節點的前面,如果insertBefore(newNode,null),則insertBefore()的操作和appendChild()一樣。

  3.replaceChild(newNode,oldNode)是將oldNode替換為newNode,不過oldNode的所有關系指針newNode也都繼承下來。

  4.removeChild(oldNode)是刪除oldNode節點。

  5.cloneNode(true/false)是將已知節點復制一份,如果為true,包括子節點,若果為false,不包括子節點。然后通過appendChild(),insertBefore(),replaceChild()將其添加到文檔中。

  6.normalize()是將空文本節點刪除或將相鄰的文本節點合並為一個文本節點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM