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


HTML DOM lastChild用法及代碼示例


DOM的lastChild屬性用於返回指定節點的最後一個孩子。它返回最後一個子節點作為文本,注釋或元素節點(取決於最後出現的子節點)。這是一個隻讀屬性。

用法:

node.lastChild

返回值:它返回一個代表該節點的最後一個子節點的節點對象,如果沒有子元素,則返回null。


範例1:

<!DOCTYPE html> 
<html> 
    <head> 
        <title> 
            DOM lastChild Property 
        </title> 
          
        <script> 
            function geek() { 
                var doc =  
                document.getElementById("div").lastChild.innerHTML; 
                  
                document.getElementById("p").innerHTML = doc; 
                document.getElementById("p").style.color = "white"; 
                document.getElementById("p").style.background = "green"; 
            } 
        </script> 
    </head> 
      
    <body style = "text-align:center;"> 
          
        <h1 style = "color:green;"> 
            GeeksforGeeks 
        </h1> 
          
        <h2> 
            DOM lastChild Property 
        </h2> 
          
        <div id = "div"> 
        <span>GeeksforGeeks! </span> 
        <span> 
            A computer science portal for geeks. 
        </span></div> 
        <br> 
        <button onclick="geek()">Click me!</button> 
          
        <p id="p"></p> 
    </body> 
</html>                    

輸出:
在單擊按鈕之前:
lastChild
單擊按鈕後:
lasChild

範例2:

<!DOCTYPE html> 
<html> 
    <head> 
        <title> 
            HTML DOM lastChild Property 
        </title> 
          
        <script> 
            function Geeks() { 
                var x =  
                document.getElementById("sel").lastChild.text; 
                  
                document.getElementById("p").innerHTML  
                        = "Last child:" + x; 
            } 
        </script> 
    </head> 
      
    <body style = "text-align:center;"> 
          
        <h1 style = "color:green;"> 
            GeeksforGeeks 
        </h1> 
          
        <h2> 
            DOM lastChild Property 
        </h2> 
          
        <select id = "sel" size = "3"> 
            <option>Merge sort</option> 
            <option>Quick sort</option> 
            <option>Insertion sort</option></select> 
        <br><br> 
          
        <button onclick = "Geeks()"> 
            Click Here! 
        </button> 
          
        <p id="p"></p> 
    </body> 
</html>                    

輸出:
在單擊按鈕之前:
lastChild
單擊按鈕後:
lasChild
支持的瀏覽器:下麵列出了lastChild屬性支持的瀏覽器:

  • 穀歌瀏覽器
  • IE瀏覽器
  • 火狐瀏覽器
  • Opera
  • 蘋果瀏覽器


相關用法


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