How to stop getting error "Unable to get property 'childNodes' of undefined or null reference?

1.2k Views Asked by At

I have a script where I am looping through a xml.responseXML and putting the childNodes[0].nodeValue into a table body. It works perfectly except when there are no results in the xml.responseXML.

The results are comments about an observation and there may be times where there are no comments. So what I want is if there are no comments to not build the table body and not throw the error "Unable to get property 'childNodes' of undefined or null reference.

I tried putting this into an if statement where if childNodes = "" then do nothing else build my table body but I haven't had any luck. As of right now every time you open an observation that doesn't have comments the browser throws an error, if it has comments then it works perfectly. Any suggestions or help would be appreciated as I am stuck.

function viewComments(xml) {            
        var i;
        var xmlDoc = xml.responseXML;
        var tbody = "";
        var x = xmlDoc.getElementsByTagName("allComments");        

        for (i = 0; i < x.length; i++) {
            tbody += "<tr><td>" +
                x[i].getElementsByTagName("COMMENT")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("DATE_COMMENT_UPDATED")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("COMMENT_ADDED_BY")[0].childNodes[0].nodeValue +
                "</td ></tr >";
        }
        $("#COMMENTS tbody").html(tbody);
        $("#COMMENTS").trigger("update");
    }
</script>

 for (i = 0; i < x.length; i++) {
            var el = x[i].getElementsByTagName("COMMENT");
            if (el.length) {
                tbody += "<tr><td>" +
                    x[i].getElementsByTagName("COMMENT")[0].childNodes[0].nodeValue +
                    "</td><td>" +
                    x[i].getElementsByTagName("DATE_COMMENT_UPDATED")[0].childNodes[0].nodeValue +
                    "</td><td>" +
                    x[i].getElementsByTagName("COMMENT_ADDED_BY")[0].childNodes[0].nodeValue +
                    "</td ></tr >";
            }
        }
0

There are 0 best solutions below