HTML - DOM 屬性 (Attr)



文件物件模型 (DOM) 中的屬性介面將元素的屬性表示為一個物件。並且,此物件表示一個 HTML 屬性,透過它我們可以控制 HTML 元素的功能。

元素的屬性儲存在一個類似陣列的無序集合中,稱為 NamedNodeMap。您可以使用其名稱或索引訪問此陣列的節點。索引從 0 開始。

例如,<img> 元素的 src 屬性定義了要顯示的影像的路徑。讓我們看看如何獲取 id 屬性的名稱 -

HTML DOM 屬性 name 屬性 - 技術教學

HTML DOM 屬性 name 屬性

點選下面的圖片獲取其屬性

image

示例

上面示例的程式碼如下:

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Attribute name Property</title>
    <style>
        .my_exe{
            width: 95%;
            padding: 10px;
            margin: 5px auto;
            background-color: rgb(197, 245, 221);
            border-radius: 10px;
            box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
            font-family: sans-serif;
        }
        .my_exe h3, .my_exe p, .my_exe img{
            text-align: center;
            justify-content: center;
            align-items: center;
        }
        .my_exe img{
            border: 1px solid green;
            border-radius: 5px;
            cursor: pointer;
            padding: 10px;
        }
        .my_exe input{
            display: block;
            width: 350px;
            padding: 10px;
            font-size: 18px;
            border-radius: 5px;
            outline: none;
            border: none;
            display: flex;
            margin: 10px auto;
        }
    </style>
</head>
<body>
    <div class="my_exe">
        <h3>HTML DOM Attribute name Property</h3>
        <p>Click on the below image to get it's attribute</p>
        <img id="demo" src="https://tutorialspoint.tw/images/logo.png" alt="demo image" onclick="printAttribute()"/>
        <input type="text" id="attribute-box" placeholder="Attribute of img tag..." readonly/>
    </div>

    <script>
        function printAttribute() {
            const element = document.getElementById("demo");
            let aName = element.attributes[0].name;
            document.getElementById("attribute-box").value = aName;
        }
    </script>
</body>

</html>

HTML DOM 屬性

下表包含 DOM 屬性列表:

序號 屬性和描述
1. value

此屬性用於設定或獲取屬性的值。

2. specified

它檢查是否指定了提到的屬性。

3. name

它用於獲取元素上使用的屬性的名稱。

4. isId

此屬性確定 HTML 屬性是否是“id”屬性。

廣告