DIV CSS 佈局教程網

JavaScript 中對 Attr(DOM 屬性)的操作詳解
編輯:JQuery特效代碼     

在 DOM 中,屬性(Attr)雖然也是一種節點,但卻無法用 firstChild、childNodes 等方式存取。以下透過範例說明如何以原生 JavaScript 對元素屬性進行讀取、修改、新增與移除。

完整程式碼如下:

<!DOCTYPE html>
<html>
<head>
  <title>DOM 操作屬性節點</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script type="text/javascript">
    function testBtn() {
        // Attr(屬性)雖然是節點,但不能用 firstChild 和 childNodes 等訪問
        // attributes 為一個屬性陣列,nodeType=2 代表屬性節點
        var myNode = document.getElementById("btn");   // 得到 element 標籤
        var x = myNode.getAttribute("id");             // 獲取該標籤的 id 屬性
        myNode.setAttribute("value", "test");          // 修改標籤的 value 屬性
        var y = myNode.getAttribute("value");
        alert("id 的屬性由「" + x + "」變成了「" + y + "」");

        // 為某元素添加屬性
        var myAtrr = document.createAttribute("class");
        myAtrr.nodeValue = "classStyle";
        myNode.setAttribute(myAtrr);

        // getAttributeNode 與 getAttribute 的區別:
        // getAttribute("") 返回屬性的值;
        // getAttributeNode("") 返回屬性節點,需再取 .value 取得節點值。
        if (myNode.getAttributeNode("class") != null)
            alert("添加成功!!");
        else
            alert("沒有添加成功");

        // 移除屬性的值
        myNode.removeAttribute("class");
        if (myNode.getAttribute("class") == null)
            alert("刪除成功!!");
        else
            alert("沒有成功");
    }
  </script>
</head>
<body>
<h1>第二章 關於 DOM</h1>
<p id="p1">DOM 簡介</p>
<p>如何使用<a href="#" name="link">DOM</a></p>
<input id="btn" type="button" onclick="testBtn()" value="測試"/>
</body>
</html>

重點整理:getAttribute() 與 setAttribute() 用於讀取與設定屬性的「值」;createAttribute() 搭配 setAttribute() 可新增屬性;removeAttribute() 則用於刪除屬性。特別要注意結尾帶有 Node 的方法(如 getAttributeNode())回傳的是屬性節點本身,而非屬性值,使用時需多加區分。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved