Christopher Vickers
Christopher Vickers

Reputation: 1953

Javascript XML - how to return a null value

<Root>
  <Child1>First Child Value</Child1>
  <Child2>
    <Age>Age1 Value</Age>
    <Age />
    <Name />
  </Child2>
  <Child3>3-1</Child3>
  <Child3>3-2</Child3>
  <Child4>4</Child4>
  <Child5>5</Child5>
  <Child6>6</Child6>
</Root>

<script>
  var xmlDoc = xml.responseXML;
  var x = xmlDoc.getElementsByTagName("Root");
  alert(y[0].getElementsByTagName("Age")[0].childNodes[0].nodeValue);
  alert(y[0].getElementsByTagName("Age")[1].childNodes[0].nodeValue);
<script>

I am trying to get a null value from "Root" > "Child2" > "Age[1]" but I get the message "0x800a138f - JavaScript runtime error: Unable to get property 'nodeValue' of undefined or null reference".

Does anyone know where I am going wrong with this?

Upvotes: 0

Views: 95

Answers (1)

Quentin
Quentin

Reputation: 943997

getElementsByTagName("Age")[1] gives you <Age />.

It has no child nodes so .childNodes[0] gives you null.

null.nodeValue is not allowed.


You need to test if y[0].getElementsByTagName("Age")[1].childNodes[0] is a true value before you try to read properties on it.

Upvotes: 1

Related Questions