0

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

2
  • did you miss </elements> by parsing there or is it missing from the xml file? Commented Jun 10, 2015 at 13:15
  • No, i just forgot to copy/paste it in the code above, sorry Commented Jun 10, 2015 at 13:17

4 Answers 4

1

Try like this

var list=xmlDoc.getElementsByTagName("product");
for (i=0;i<list.length;i++)
{
     if(list[i].getAttribute("id")==2){
        // Found your node
     }
} 
Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

1
var node = xmlDoc.getElementsByTagName("product");
for (var index in node) {
    if (node[index].getAttribute("id") == "2") {
        alert();
    }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.