I am making a page which creates a datagrid from the data in a xml file. Apart from other columns, there are 7 columns for author names and it should contain min 1 author and max 7. I have this XML file that have records tagged as <author1></author>.. <author2>.... and so on. Those with less than 7 authors are obviously empty. In my javascript code, i used: author2= document.createTextNode(x[i].getElementsByTagName("author2")[0].childNodes[0].nodeValue) || "blank"; Code (markup): and also used author2= document.createTextNode(x[i].getElementsByTagName("author2")[0].childNodes[0].nodeValue); if( author2 === undefined) author2=""; td6.appendChild(author2); Code (markup): But none of them are working if author 2 is empty. The error m getting is: Error: x.getElementsByTagName("author2")[0] is undefined Source File: file:///F:/script.js Line: 107 I googled a lot but just couldnt get this thing working. Please help me out here. How do i handle undefined values while parsing XML
Try to check the length of getElementsByTagName() first before using it? If it returns zero, then you might set author2 to "blank" or just "". Hendra
Not working.. Now it gives the error on the line where i am checking its length. I guess i have to make some sort of check before using -- x.getElementsByTagName("author2")[0].childNodes[0].nodeValue
ok i got the actual problem. I didnt noticed that there was no author2 in xml file. Actually i created the xml through excel sheet and for the blank cells, excel didnt create any empty <author2></author2> tags. Thats y the getElementsById didnt responded. Now should i go the inappropriate way of including all the empty tags in the xml file or there is some other way ? Any syntax where i can check is a particular tag exists or not ?
I would think that if the x is a valid XML document, then (x.getElementsByTagName) would return true (a function), and you could use appropriately the getElementsByTagName(). So provided that condition, even if there's no <author2> element in (x.getElementsByTagName().length) shouldn't give you an error. Are you using an example from http://www.w3schools.com/dom/dom_parser.asp?
Not this one but some other ones on w3schools. I got this syntax(getElementsByTagName("author2")[0].childNodes[0].nodeValue) from w3schools and createTextNode from other sites. Also, if i put the author2 processing lines in a try catch block, the statements are throwing an error. So surely it is not working for non existing author2 tags
you can try this.. if(x[i] && x[i].getElementsByTagName("author2") && x[i].getElementsByTagName("author2")[0] && x[i].getElementsByTagName("author2")[0].childNodes[0]) author2= document.createTextNode(x[i].getElementsByTagName("author2")[0].childNodes[0].nodeValue); else author2= "blank"; Code (markup):