0

I have xml as follows:

<a>
  <a>
    <d>0</d>
  </a>
  <a>
    <d>99</d>
  </a>
</a>

This is my code javascript.

var a = document.getElementsByTagName("a");
var d = a[1].getElementsByTagName("d")[0].firstChild.data;
document.write("d = " + d);

The result is d = 0 but my expected result is d = 99.

Could you help me please?

I want to input only index 1 (a[1]) i do not want to input index 2.

Bell Aimsaard
  • 483
  • 3
  • 5
  • 16
  • Possible duplicate https://stackoverflow.com/questions/4495569/how-do-i-retrieve-the-value-of-a-specific-xml-node-by-path – Niladri Sep 16 '17 at 14:55
  • 1
    Possible duplicate of [How do I retrieve the value of a specific XML node by path?](https://stackoverflow.com/questions/4495569/how-do-i-retrieve-the-value-of-a-specific-xml-node-by-path) – Bakudan Sep 16 '17 at 15:14

2 Answers2

1

You can use DOMParser function to create a xmlDoc and than read from it required value. The problem was in your element selector.

var text = "<a> <a> <d>0</d></a><a><d>99</d></a></a>"
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
var dNode = xmlDoc.querySelectorAll('a a:last-child d')[0];
var dNodeValue = dNode.innerHTML;

console.log(dNodeValue);
// 99
anshu purohit
  • 176
  • 2
  • 10
0

So basically you are looking for a[2]:

<a> <-- a[0]
  <a>  <-- a[1]
    <d>0</d>
  </a>
  <a>  <-- a[2]
    <d>99</d>
  </a>
</a>

Here is the update:

var a = document.getElementsByTagName("a");
var d = a[2].getElementsByTagName("d")[0].firstChild.data;
          ^---- this is what changed
document.write("d = " + d);
Dekel
  • 60,707
  • 10
  • 101
  • 129