Jump to content

checking for an empty node when using getElementsByTagName


knee_boarder

Recommended Posts

I'm using getElementsByTagName to access the data in an xml field eg.

x[i].getElementsByTagName("club")[0].childNodes[0].nodeValue

and as an empty node causes my Javascript to error, I want to check if there is anything in the node before I attempt to get anything out of the field.I'm failing miserably to do this and my googling is just confusing me!Any help would be seriously appreciated!

Link to comment
Share on other sites

You need to test for the existence of properties before you try to access them. This is especially true when you are testing chained properties. If one is missing 3 links from the end, it's a sure bet the last one isn't there.I forget if every browser assigns a childNodes property to every node whether there are childNodes or not. So it might be wise to start there:

var el = x[i].getElementsByTagName("club")[0];if (el.childNodes && el.childNodes.length > 0) {   // access the nodeValue}else {   // don't}

If you do a lot of that sort of thing, you'll end up repeating yourself a lot. Writing a little utility function around code like that could simplify the job.

Link to comment
Share on other sites

You need to test for the existence of properties before you try to access them. This is especially true when you are testing chained properties. If one is missing 3 links from the end, it's a sure bet the last one isn't there.I forget if every browser assigns a childNodes property to every node whether there are childNodes or not. So it might be wise to start there:
var el = x[i].getElementsByTagName("club")[0];if (el.childNodes && el.childNodes.length > 0) {   // access the nodeValue}else {   // don't}

If you do a lot of that sort of thing, you'll end up repeating yourself a lot. Writing a little utility function around code like that could simplify the job.

Thanks very much for that I'll give it a go tonight :)
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...