怎樣獲取當前節點的父節點或父元素節點


獲取父節點: Node.prototype.parentNode

獲取父節點元素: Node.prototype.parentElement

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="id1">李雷</div>
    <script>
        var id1 = document.getElementById("id1");
        document.getElementById("id1").parentNode;
        document.getElementById("id1").parentNode.parentNode;
        document.getElementById("id1").parentNode.parentNode.parentNode;
        document.getElementById("id1").parentNode.parentNode.parentNode.parentNode;
    </script>
</body>
</html>

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="id1">李雷</div>
    <script>
        var id1 = document.getElementById("id1");
        document.getElementById("id1").parentElement;
        document.getElementById("id1").parentElement.parentElement;
        document.getElementById("id1").parentElement.parentElement.parentElement;
    </script>
</body>
</html>

 

 

父節點有三種類型: 元素節點(element)、文檔節點(document)和文檔片段節點(documentfragment), .parentNode 可能返回這三個類型中的一個. 

父元素節點排除了documentdocumentfragment, 只會返回元素節點.

 

注意, 如果對element和documentfragment使用, 則返回null

 


免責聲明!

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



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