HTML - DOM 元素 hasAttribute() 方法



**hasAttribute()** 方法檢查 HTML 元素中是否存在某個屬性。如果屬性存在,則返回“true”,否則返回“false”,表示該屬性不存在。

語法

element.hasAttribute(name);

引數

引數 描述
name 表示屬性名稱的字串。

返回值

如果 HTML 元素上存在該屬性,則該方法返回布林值“true”;否則返回“false”。

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

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

檢查特定屬性

此示例演示如何使用 hasAttribute() 方法透過返回 true 或 false 來檢查特定屬性。

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

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasAttribute() Method</h2>
    
    <div id="exampleDiv" title="Sample Div">
        Does the div have a title attribute?
    </div>  
    
    <p id="attributeInfo"></p>

    <script> 
        const divElement = document.getElementById
        ('exampleDiv');
        const hasTitle = divElement.hasAttribute
        ('title');
        document.getElementById
        ('attributeInfo').textContent = 
        hasTitle.toString(); 
    </script>
</body>

</html>

檢查多個屬性

此示例演示如何使用 hasAttribute() 方法檢查特定屬性,然後在單擊按鈕時顯示結果。它檢查 ID 為 exampleDiv 的**<div>**元素是否具有 title 和 data-info 屬性。

<!DOCTYPE html>
<html>
<head>  
    <title>
        HTML DOM Element hasAttribute() Method
    </title>
</head>;

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasAttribute() Method</h2>
    <div id="exampleDiv" title="Div" data-info="12345">
       Hello!I am Div.Check my attributes?Hit the button!
    </div>
    <br>
    <button onclick="displayAttributes()">
        Display Attributes
    </button>

    <script>
        function displayAttributes() {
            const divElement = document.getElementById
            ('exampleDiv');
            const hasTitle = divElement.hasAttribute
            ('title');
            const hasDataInfo = divElement.hasAttribute
            ('data-info');

            alert(`Title attribute: ${hasTitle}
            \nData-info attribute: ${hasDataInfo}`);
        }
    </script>
</body>

</html>

處理屬性不存在的情況

此示例幫助我們瞭解如何使用 hasAttribute() 檢查屬性是否存在並相應地顯示訊息,如果屬性存在則返回 true,如果屬性不存在則返回 false。

<!DOCTYPE html>
<html lang="en">
<head>  
    <title>
        Handling missing Attribute
    </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>hasAttribute() Method</h2>
    <div id="exampleDiv">
        Does Div have any attributes?
    </div>

    <button onclick="displayAttributes()">
        Display Attributes
    </button>
    
    <p id="attributeInfo"></p>
    <script>
        function displayAttributes() {
            const divElement = document.getElementById
            ('exampleDiv');
            const hasTitle = divElement.hasAttribute
            ('title');
            document.getElementById
            ('attributeInfo').textContent = 
                `false - It has ${hasTitle ?
                 'title' : 'no'} attribute.`;
        }
    </script>
</body>

</html>

支援的瀏覽器

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