Prevent javascript from breaking when xml has an empty node value

I have an xml example:

<LOCAL_AUTHORITY>
     <NAME>Derby</NAME>
     <REGION></REGION>
     <IRD>22%</IRD>
<LOCAL_AUTHORITY>

I have the following javascript:

localAuthorities=xmlDoc.getElementsByTagName("LOCAL_AUTHORITY");
alert(localAuthorities[0].getElementsByTagName("REGION")[0].childNodes[0].nodeValue);
alert('This get triggered so javascript is not broken');

My question is javascript breaks if you don't give the region a value in xml. Good reactions to any respondents. How can I prevent it from breaking?

+3
source share
2 answers

You need to make sure that there is something before you read it. main idea:

var nodes = localAuthorities[0].getElementsByTagName("REGION")[0].childNodes;
var value = nodes.length===1 ? nodes[0].nodeValue : "";
alert(value);
+1
source

You can do:

localAuthorities=xmlDoc.getElementsByTagName("LOCAL_AUTHORITY");
// validate if there is region or not
if (localAuthorities[0].getElementsByTagName("REGION")[0].val()){
  alert(localAuthorities[0].getElementsByTagName("REGION")[0].childNodes[0].nodeValue);
  alert('This get triggered so javascript is not broken');
}
-1
source

All Articles