當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML DOM parentElement用法及代碼示例


DOM parentElement屬性用於返回特定子元素的父元素。這是一個隻讀屬性。 parentElement和parentNode屬性相似,唯一的區別是,如果父節點不是元素,則parentElement屬性返回null。

用法:

node.parentElement

返回值:它返回一個表示任何子節點的父節點的字符串;如果指定的節點不包含任何父節點,則返回null。


範例1:

<!DOCTYPE html> 
<html> 
    <head> 
        <title> 
            HTML DOM parentElement Property 
        </title> 
    </head> 
      
    <body> 
        <h1 style = "color:green;"> 
            GeeksForGeeks 
        </h1> 
          
        <h2>DOM parentElement Property</h2> 
          
        <ol type = "1"> 
            <li id = "GFG">Quick Sort</li> 
            <li>Merge Sort</li> 
            <li>Selection Sort</li> 
            <li>Heap Sort</li> 
        </ol> 
          
        <button onclick="Geeks()"> 
            Submit 
        </button> 
          
        <p id="sudo"></p> 
          
        <!-- script to find parentElement -->
        <script> 
            function Geeks() { 
            var w =  
                document.getElementById("GFG").parentElement.nodeName; 
            document.getElementById("sudo").innerHTML = w; 
            } 
        </script> 
    </body> 
</html>                    

輸出:
在單擊按鈕之前:

單擊按鈕後:

範例2:本示例隱藏父元素以單擊關閉圖標。

<!DOCTYPE html> 
<html> 
    <head> 
        <title> 
            HTML DOM parentElement Property 
        </title> 
          
        <!-- CSS property to create box-->
        <style> 
            div { 
                padding:16px; 
                width:70%; 
                background-color:green; 
                color:white; 
                border-radius:30px; 
            } 
            .GFG { 
                float:right; 
                font-size:30px; 
                font-weight:bold; 
                cursor:pointer; 
            } 
        </style> 
    </head> 
      
    <body> 
        <center> 
            <h2>DOM parentElement Property</h2> 
              
            <div> 
                <span class = "GFG"
                      onclick = "this.parentElement.style.display
                              = 'none';"> 
                 &times 
                </span> 
                  
                <p style="font-size:30px;">GeeksforGeeks.</p> 
            </div> 
        </center> 
    </body> 
</html>                    

輸出:
在點擊十字圖標之前:

單擊十字圖標後:

支持的瀏覽器:DOM parentElement屬性支持的瀏覽器如下:

  • 穀歌瀏覽器1.0
  • IE瀏覽器
  • Firefox 9.0
  • Opera
  • 蘋果瀏覽器


相關用法


注:本文由純淨天空篩選整理自ManasChhabra2大神的英文原創作品 HTML | DOM parentElement Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。