Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking if node exists before accessing data

Status
Not open for further replies.

kneeboarder

Programmer
Feb 1, 2011
3
GB
If I'm looping through the xml and using getElementsByTagName -

Code:
x[i].getElementsByTagName("fieldname")[0].childNodes[0].nodeValue

is there a way of checking whether that node exists?

This errors if the field is empty or the field doesn't exist at all so I want to test first before trying to get the actual value.
 
someone has suggested this

Code:
var el = x[i].getElementsByTagName("fieldname")[0];
if (el.childNodes && el.childNodes.length > 0) {
   // access the nodeValue
}
else {
   // don't
}
 
This is a quick fix.
[tt]
var el = x.getElementsByTagName("fieldname"[highlight]);[/highlight]
if (el[red][0][/red] && el[0].childNodes[0]) {
// access the nodeValue (el[0].childNodes[0].nodeValue
}
else {
// don't
}[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top