XML DOM setAttribute() 方法
XML基础 2023-08-13 15:13:322小码哥的IT人生shichen
XML DOM setAttribute() 方法
定义和用法
setAttribute() 方法创建或改变某个新属性。
语法:
elementNode.setAttribute(name,value)
参数 | 描述 |
---|---|
name | 必需。规定要设置的属性名。 |
value | 必需。规定要设置的属性值。 |
说明
该方法把指定的属性设置为指定的值。如果不存在具有指定名称的属性,该方法将创建一个新属性。
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
下面的代码片段向 "books.xml" 中的所有 <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("<br />"); }
输出:
Everyday Italian - Edition: FIRST Harry Potter - Edition: FIRST XQuery Kick Start - Edition: FIRST Learning XML - Edition: FIRST
TIY
完整实例【setAttribute() - 改变属性的值】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); var 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>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
完整实例【setAttribute() - 创建新的属性和属性值】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); var x=xmlDoc.getElementsByTagName('book'); for(i=0;i<x.length;i++) { x.item(i).setAttribute("edition","FIRST"); } //Output book title and edition value var 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("<br />"); } </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html