当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。