HTML - DOM 元素 hasAttributes() 方法



hasAttributes() 方法檢查 HTML DOM 中的元素是否具有屬性。如果元素具有一個或多個屬性,則返回“true”,否則返回“false”。

注意:hasAttribute() 方法檢查特定屬性的存在,而 hasAttributes() 方法檢查元素是否根本有任何屬性。

語法

element.hasAttributes();

返回值

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

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

以下是一些 hasAttribute() 方法的示例,它檢查 HTML DOM 元素中特定屬性的存在。

檢查 Div 元素是否有任何屬性

此示例演示如何使用 hasAttribute() 方法檢查任何屬性,然後在單擊按鈕時顯示結果。它檢查id=exampleDiv 的<div>元素是否具有任何屬性。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>
        HTML DOM Element hasAttributes() Method
    </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasAttributes() Method</h2>  

    <div id="exampleDiv" title="Sample Div">
        Does it has any attributes?
    </div>
    <br>
    <button onclick="checkAttributes()">
       Check Attributes
    </button>
    <p id="result"></p>

    <script>
        function checkAttributes() {
            const divElement = document.getElementById
            ('exampleDiv');   

            document.getElementById('result').textContent=
               "The div has attributes.";
            
        }
    </script>
</body>

</html>

檢查 Body 元素的屬性

此示例檢查 body 元素是否具有任何屬性。由於此示例中的 body 元素沒有任何屬性,因此 hasAttributes() 方法返回 false 並顯示相應的訊息。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>
        HTML DOM Element hasAttributes() Method
    </title>
</head>

<body>
    <h1>HTML - DOM Element </h1>
    <h2>hasAttributes() Method</h2>
    <p>Does Body element has any attribute?</p>
    
    <button onclick="checkAttributes()">
        Check Body Attributes
    </button>
    <p id="result"></p>

    <script>
        function checkAttributes() {
            const bodyElement = document.body; 
            document.getElementById('result').textContent= 
            "Body element does not have any attributes.";
        }
    </script>
</body>

</html>

檢查錨標籤是否具有屬性

此示例檢查錨點(<a>)標籤在 HTML 元素中是否具有任何屬性,並相應地顯示訊息。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>
        HTML DOM Element hasAttributes() Method
    </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasAttributes() Method</h2> 
    <p>Checks if Anchor tag has any Attributes</p> 
    
    <a id="myLink" href=
"https://tutorialspoint.tw/">
        Example Link
    </a>
    
    <button onclick="checkAttributes()">
        Check Attributes
    </button>
    <p id="result"></p>
    
    <script>
        function checkAttributes() {
            const linkElement = document.getElementById
            ('myLink');                       
            document.getElementById('result').textContent = 
            "The link has attributes.";      
        }
    </script>
</body>

</html>    

支援的瀏覽器

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