getNamedItem() 方法返回指定的节点。
getNamedItem(nodename)
| 参数 | 描述 |
|---|---|
| nodename | 要检索的节点名称。 |
下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,循环遍历 <book> 元素并打印 category 属性的值:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
for(i=0;i<x.length;i++)
{
att=x.item(i).attributes.getNamedItem("category");
document.write(att.value + "
");
}
上面的代码将输出:
COOKING
CHILDREN
WEB
WEB
getNamedItem() - 改变某个项目的值
<!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++)
{
attlist=x.item(i).attributes;
att=attlist.getNamedItem("category");
att.value="BESTSELLER";
}
//Output all attribute values
for (i=0;i<x.length;i++)
{
document.write(x[i].getAttribute('category'));
document.write("<br>");
}
</script>
</body>
</html>