0
我該如何着手設置屬性,但僅限於具有特定值的元素?Javascript XML DOM將屬性設置爲特定元素
例如:
<Farm>
<animals>
<type>chicken</type>
<age>1</age>
</animals>
<animals>
<type> Cat</type>
<age>4</age>
</animals>
<animals>
<type>Cow</type>
<age> 3</age>
</animals>
</farm>
如何讓我的JavaScript文件,將屬性添加到具有牛的元素?添加具有值的元素:名稱:Fred。
我試過這個,它添加了屬性NOT THE VALUE,但它也將它添加到所有元素中。
function get_firstchild(n) {
x = n.firstChild;
while (x.nodeType != 1) {
x = x.nextSibling;
}
return x;
}
xmlDoc = loadXMLDoc("A74.xml");
x = xmlDoc.documentElement;
firstNode = get_firstchild(x);
for (i = 0; i < firstNode.childNodes.length; i++) {
if (firstNode.childNodes[i].nodeType == 1) {
document.write("<br>Node Name: " + firstNode.childNodes[i].nodeName + "<br>");
document.write("Node Type: " + firstNode.childNodes[i].nodeType + "<br>");
document.write("Node Value: " + firstNode.childNodes[i].childNodes[0].nodeValue + "<br>");
document.write("");
}
}
x=xmlDoc.getElementsByTagName("animals");
for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("name","Fred");
}
//Output book title and edition value
x=xmlDoc.getElementsByTagName("type");
for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write(" - name: ");
document.write(x[i].parentNode.getAttribute('name'));
document.write("");
}
加上面我試過,加的屬性而不是價值。和所有元素。 – CodedMe