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.

2

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

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.