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


HTML DOM children用法及代碼示例


DOM子元素屬性用於返回指定元素的所有子元素的HTMLcollection。集合中的元素可以通過索引號訪問。它與childNodes不同,因為childNodes包含所有節點(即,它也包含文本和注釋節點),但另一方麵,子級僅包含元素節點。這是一個隻讀屬性。

用法:

element.children

返回值:它返回可以通過索引訪問的元素節點的集合。


範例1:本示例返回列表項的數量。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML DOM children Property 
    </title> 
  
    <!-- Script to count children of parent attribute -->
    <script> 
        function Geeks() { 
            var count = 
                document.getElementById("parent").children.length; 
  
            document.getElementById("p").innerHTML =  
                  "No of Children:" + count; 
        } 
    </script> 
</head> 
  
<body> 
    <h1>GeeksforGeeks</h1> 
  
    <h2> 
            DOM children Property 
        </h2> 
  
    <p>Searching Algorithms</p> 
  
    <ul id="parent"> 
        <li>Merge sort</li> 
        <li>Quick sort</li> 
    </ul> 
  
    <button onclick="Geeks()"> 
        Click Here! 
    </button> 
  
    <p id="p"></p> 
</body> 
  
</html>

輸出:
在單擊按鈕之前:
children
單擊按鈕後:
children

範例2:

<!DOCTYPE html> 
<html> 
    <head> 
        <title> 
            HTML DOM children Property 
        </title> 
          
        <script> 
            function Geeks() { 
                var doc =  
                document.getElementById("parent").children; 
                  
                var i; 
                for(i = 0; i < doc.length; i++) { 
                    doc[i].style.color = "white"; 
                    doc[i].style.backgroundColor = "green"; 
                } 
            } 
        </script> 
    </head> 
      
    <body style = "text-align:center"> 
          
        <h1 style = "color:green;"> 
            GeeksforGeeks 
        </h1> 
          
        <h2> 
            DOM children Property 
        </h2> 
          
        <div id = "parent"> 
            <p> 
                A computer science portal for geeks. 
            </p> 
            <p> 
                Geeks classes an extensive programme for geeks. 
            </p> 
        </div> 
          
        <button onclick = "Geeks()">Click me!</button> 
    </body> 
</html>                    

輸出:
在單擊按鈕之前:
children
單擊按鈕後:
children

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

  • 穀歌瀏覽器2.0
  • Internet Explorer 9.0 *
  • Firefox 3.5
  • Opera 10.0
  • 蘋果Safari 4.0


相關用法


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