XML DOM setAttribute() 方法


Element 對象參考手冊 Element 對象

定義和用法

setAttribute() 方法添加新屬性。

如果元素中已經存在指定名稱的屬性,它的值更改為 value 參數的值。

語法

elementNode.setAttribute(name,value)

參數 描述
name 必需。規定要設置的屬性的名稱。
value 必需。規定要設置的屬性的值。


實例

下麵的代碼片段使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中,並向所有 <book> 元素添加 "edition" 屬性:

實例

xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName('title'); // 為每個 title 元素添加新屬性 for(i=0;i<x.length;i++) { x[i].setAttribute("edition","first"); } // 輸出 title 和 edition 值 for (i=0;i<x.length;i++) { document.write(x[i].childNodes[0].nodeValue); document.write(" - Edition: "); document.write(x[i].getAttribute('edition')); document.write("<br>"); }

輸出:

Everyday Italian - Edition: FIRST
Harry Potter - Edition: FIRST
XQuery Kick Start - Edition: FIRST
Learning XML - Edition: FIRST


嘗試一下

setAttribute() - 改變屬性的值


Element 對象參考手冊 Element 對象