Bell Aimsaard
Bell Aimsaard

Reputation: 505

Get Element in xml by using javascript

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.

Upvotes: 0

Views: 56

Answers (2)

anshu purohit
anshu purohit

Reputation: 176

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

Upvotes: 1

Dekel
Dekel

Reputation: 62676

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);

Upvotes: 0

Related Questions