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


HTML DOM hasChildNodes()用法及代碼示例


如果給定節點具有子節點,則HTML hasChildNodes()屬性將返回true,否則將返回false。空白行或空白也被視為子節點,因此它在空白行或空白中也返回true。先決條件DOM(文檔對象模型)

參數:
無需參數。

返回值:HTML nodeValue屬性返回以下類型的值。


  • 真正如果給定的節點具有子級或空格或空白行。
  • 如果給定的節點沒有任何孩子。

用法

node.hasChildNodes()

示例1:在以下段落中,標記沒有任何內容,因此返回false

<!DOCTYPE html> 
<html> 
  
<body> 
  
    <head> 
        <script> 
  
            // utility function to demonstarte hasChildNode  Property 
            function exampleFunction() { 
                
                // var x used to get the information of those node  
                // for which you want to perform  
                // hasChildNode properties 
                var res =  
                document.getElementById("divId").hasChildNodes(); 
                
                document.getElementById("GeeksForGeeks"+ 
                ).innerHTML = res; 
            } 
        </script> 
    </head> 
  
    <!--In this example we will create a node of the type div 
     and a button which calls a function name "exampleFunction"  
     on clicking of this button it will show the properties of  
     hasChildNode property -->
    <p id="divId"></p> 
    <br> 
  
    <button onclick="exampleFunction()"> 
      click to know the paragraph tag has any child node 
    </button> 
    
    <!-- below paragraph Tag is used to  
    print the value of nodeValue properties-->
    <p id="GeeksForGeeks"></p> 
</body> 
  
</html>

輸出:

例2:在下麵的段落中,標簽有一個消息,因此返回true

<!DOCTYPE html> 
<html> 
  
<body> 
  
    <head> 
  
        <script> 
  
            // utility function to demonstarte hasChildNode Property 
            function exampleFunction() { 
  
                // var x used to get the information of those nodes 
                // for which you want to perform  
                // hasChildNode properties. 
                var res =  
                document.getElementById("divId").hasChildNodes(); 
                
                document.getElementById("GeeksForGeeks"+ 
                ).innerHTML = res; 
            } 
        </script> 
    </head> 
    <!--In this example we will create a node of the type div 
     and a button which calls a function name "exampleFunction"  
     on clicking of this button it will show the properties of  
     hasChildNode property -->
    <p id="divId">Hello geeksforgeeks</p> 
    <br> 
  
    <button onclick="exampleFunction()"> 
      click to know the paragraph tag has any child 
    </button> 
    
    <!-- below paragraph Tag is used to print the  
         value of nodeValue properties-->
    <p id="GeeksForGeeks"></p> 
</body> 
  
</html>

輸出:

支持的瀏覽器:DOM click()方法支持的瀏覽器如下:

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


相關用法


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