HTML - DOM 元素的 hasChildNodes() 方法



**hasChildNodes()** 方法用於檢查 HTML 元素內部是否包含任何子元素。如果存在子節點,則返回“true”,否則返回“false”。

語法

element.hasAttributes();

返回值

此方法返回一個布林值“true”,如果元素具有子節點;否則返回“false”。

HTML DOM 元素“hasChildNodes()”方法的示例

以下是 hasChildNodes() 方法的一些示例,這些示例檢查 HTML DOM 元素內是否存在子節點。

檢查元素是否具有子節點

此示例演示如何使用 hasChildNodes() 方法檢查是否存在任何子節點,並在單擊按鈕時顯示結果。它檢查 id=parentElement 的**<div>** 元素是否具有任何子節點。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>Checks for Child Nodes</title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasChildNodes() Method</h2>
    <p>
        Checks if the element has child nodes.
    </p>
    <div id="parentElement">
        <p>Does this div have child nodes?</p>
    </div>
    <button onclick="checkChildNodes()">
        Check Child Nodes
    </button>

    <script>
        function checkChildNodes() {
            const parentElement = 
            document.getElementById('parentElement');
            if (parentElement.hasChildNodes()) {
                alert
                ('The parent element has child nodes.');
            } else {
                alert
                ('Parent element doesn`t have child nodes.'
                );
            }
        }
    </script>
</body>

</html>
       

動態新增和檢查子節點

此示例在單擊按鈕時動態新增一個子節點,然後透過單擊“檢查子節點”按鈕來檢查元素是否具有任何子節點。因此,如果添加了子節點,它將顯示它具有子節點,如果沒有,則將顯示相應的訊息。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>
        Checks for the Child nodes Dynamically
    </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasChildNodes() Method</h2>
    <p>
        Add child nodes by clicking the button!!
    </p>
    <div id="parentElement"></div>
    <button onclick="addTextNode()">
        Add Child Node
    </button>
    <p>Checks for the child Nodes..</p>
    <button onclick="checkChildNodes()">
        Check Child Nodes
    </button>
    <p><b>Note:</b> No child nodes will be displayed 
            if none have been added.
    </p>  
    <script>
        function addTextNode() {
            const parentElement = 
            document.getElementById('parentElement');
            const textNode = document.createTextNode
            ('Text node added.');
            parentElement.appendChild(textNode);
        }

        function checkChildNodes() {
            const parentElement = document.getElementById
            ('parentElement');
            if (parentElement.hasChildNodes()) {
                alert('Parent element has child nodes.');
            } else {
                    alert('Parent has no child nodes.');
            }
        }
    </script>
</body>

</html>    

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
hasChildNodes()
html_dom_element_reference.htm
廣告