How to handle empty XML fields in JS in JavaScript Posted October 4, 2005 I'm using JavaScript to retrieve info from an XML file, but if any of the fields are empty I get this error: Error: xmlDocument.getElementsByTagName("address2Title")(0).firstChild has no propertiesSource File: http://localhost/contactManager/Line: 47Here's an example of the XML file:<contact> <id>2</id> <firstName>First Name</firstName> <lastName>Last Name</lastName> <address1Title>Home</address1Title> <address1>101 Blah St</address1> <city1>Dayton</city1> <state1>Ohio</state1> <zipCode1>45402</zipCode1> <address2Title/> <address2/> <city2/> <state2/> <zipCode2/> <homePhone>9375559407</homePhone> <cellPhone>9375556845</cellPhone> <workPhone/> <birthday>01311978</birthday></contact> And here's the relevant JS code document.getElementById("contactInfo").innerHTML = xmlDocument.getElementsByTagName('firstName').item(0).firstChild.nodeValue +xmlDocument.getElementsByTagName('lastName').item(0).firstChild.data +xmlDocument.getElementsByTagName('address1Title').item(0).firstChild.data +xmlDocument.getElementsByTagName('address1').item(0).firstChild.data +xmlDocument.getElementsByTagName('city1').item(0).firstChild.data +xmlDocument.getElementsByTagName('state1').item(0).firstChild.data +xmlDocument.getElementsByTagName('zipCode1').item(0).firstChild.data +xmlDocument.getElementsByTagName('address2Title')(0).firstChild.nodeValue +xmlDocument.getElementsByTagName('address2').item(0).firstChild.data +xmlDocument.getElementsByTagName('city2').item(0).firstChild.data +xmlDocument.getElementsByTagName('state2').item(0).firstChild.data +xmlDocument.getElementsByTagName('zipCode2').item(0).firstChild.data +xmlDocument.getElementsByTagName('homePhone').item(0).firstChild.data +xmlDocument.getElementsByTagName('cellPhone').item(0).firstChild.data +xmlDocument.getElementsByTagName('workPhone').item(0).firstChild.data +xmlDocument.getElementsByTagName('birthday').item(0).firstChild.data; Is there a way to access the field that won't cause an error if it's empty, or is there a way to check if it's empty before trying to use it?
How to handle empty XML fields in JS
in JavaScript
Posted
I'm using JavaScript to retrieve info from an XML file, but if any of the fields are empty I get this error:
Here's an example of the XML file:And here's the relevant JS code
Is there a way to access the field that won't cause an error if it's empty, or is there a way to check if it's empty before trying to use it?