HTML - DOM 屬性名稱屬性



HTML DOM 屬性 name 屬性用於獲取元素上使用屬性的名稱。name 屬性是隻讀屬性,這意味著此屬性無法更改 HTML 元素的屬性。

語法

attribute.name

返回值

name 屬性返回指定索引的屬性名稱。

HTML DOM 屬性“name”屬性示例

以下是一些示例程式碼,說明如何在 JavaScript 和 HTML 中使用“name”屬性。

獲取第一個屬性的名稱

以下程式碼演示如何使用 name 屬性獲取 HTML 標籤屬性的名稱。

<!DOCTYPE html>
<html>

<head>
    <title>HTML DOM Attribute name Property</title>
</head>

<body>
    <h3>HTML DOM Attribute name Property</h3>
    <p>
        The name property of DOM returns 
        the name of an attribute
    </p>

    <div id="demo"></div>

    <script>
        const element = document.getElementById("demo");

        // This will select name of first attribute of div
        let aName = element.attributes[0].name;
        // Pass the name to inside of div tag
        document.getElementById("demo").innerHTML = aName;
    </script>
</body>

</html>

獲取所有屬性的名稱

在這裡,我們將執行一個簡單的 for 迴圈來獲取 HTML 元素的所有屬性的名稱。

<!DOCTYPE html>
<html>

<head>
    <title>HTML DOM Attribute name Property</title>
</head>

<body>
    <h3>HTML DOM Attribute name Property</h3>
    <p>
        The name property of DOM returns 
        the name of attributes
    </p>

    <div id="demo" 
         class="exampleClass" 
         data-info="someData">
    </div>

    <script>
        const element = document.getElementById("demo");

        // Initialize an empty array to hold attribute names
        let attributeNames = [];

        // Loop through all attributes of the element
        for (let i = 0; i < element.attributes.length; i++) {
            attributeNames.push(element.attributes[i].name);
        }

        // Join the attribute names with commas 
        // and pass them inside the div tag
        document.getElementById("demo").innerHTML = 
        attributeNames.join(", ");
    </script>

</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
name
廣告