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 对象

0 个评论

要回复文章请先登录注册