dd

XML DOM setAttribute() 方法


定义和用法

setAttribute() 方法添加新属性。

如果元素中已经存在指定名称的属性,它的值更改为 value 参数的值。

语法

elementNode.setAttribute(name,value)


参数描述
name必需。规定要设置的属性的名称。
value必需。规定要设置的属性的值。

实例

下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,并向所有 <book> 元素添加 "edition" 属性:

实例

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book");

for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("edition","first");
}

//Output book title and edition value
x=xmlDoc.getElementsByTagName("title");
for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write(" - Edition: ");
document.write(x[i].parentNode.getAttribute('edition'));
document.write("
");
}

输出:

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

尝试一下 Demos

setAttribute() - 改变属性的值

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName('book');

for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("category","BESTSELLER");
}
  
//Output all attribute values
for (i=0;i<x.length;i++)
{
document.write(x[i].getAttribute('category'));
document.write("<br>");
}
</script>
</body>
</html>