Reputation: 297
In that XML :
<elements>
<product id="1">
<brand>xxxxxxx</brand>
<dci>xxxxx</dci>
<therapeutic_area>xxxxxx</therapeutic_area>
</product>
<product id="2">
<brand>xxxxxx</brand>
<dci>xxxx</dci>
<therapeutic_area>xxxx</therapeutic_area>
</product>
<product id="3">
<brand>xxx</brand>
<dci>xxxx</dci>
<therapeutic_area>xxxxx</therapeutic_area>
</product>
I need to select the node which has a specific attribute value. For instance 2
I tried this but it does not work:
alert(xmlDoc.getElementsByTagName("product")[0].getAttributeNode("2"));
Thanks in advance for your help
Upvotes: 0
Views: 120
Reputation: 1990
I really don't understand what your trying to do here, but try something like this.
alert(document.querySelector("[id='2']").querySelector('brand'));
see querySelector.
Upvotes: 0
Reputation: 7117
var node = xmlDoc.getElementsByTagName("product");
for (var index in node) {
if (node[index].getAttribute("id") == "2") {
alert();
}
}
Upvotes: 1
Reputation: 7446
var xmlfile = "<elements><product id=\"1\"><brand>xxxxxxx</brand><dci>xxxxx</dci><therapeutic_area>xxxxxx</therapeutic_area></product><product id=\"2\"><brand>xxxxxx</brand><dci>xxxx</dci><therapeutic_area>xxxx</therapeutic_area></product><product id=\"3\"><brand>xxx</brand><dci>xxxx</dci><therapeutic_area>xxxxx</therapeutic_area></product></elements>";
var parser = new DOMParser();
xmlDocument = parser.parseFromString(xmlfile,"text/xml");
var products = xmlDocument.getElementsByTagName("product");
for (var i = 0; i < products.length; ++i) {
if (products[i].getAttribute("id") == 2) {
// product id is 2.
}
}
http://jsfiddle.net/dvgLhw66/ <-- working fiddle.
You are using the wrong prototype. getAttributeNode does not exist, you're looking for getAttribute.
Upvotes: 1
Reputation: 25352
Try like this
var list=xmlDoc.getElementsByTagName("product");
for (i=0;i<list.length;i++)
{
if(list[i].getAttribute("id")==2){
// Found your node
}
}
Upvotes: 1