Uncaught TypeError: Cannot call method 'hasChildNodes' of undefined

I am trying to read a XML using ajax request in jquery. Below is the code,it's working fine in IE but when I run this on Chrome i am facing this error

Uncaught TypeError: Cannot call method 'hasChildNodes' of undefined

$.ajax({

    type: "GET",
    url: "tree1.xml",
    dataType:"xml",
    success: function(xml){
        root=xml.documentElement;
        childs=root.childNodes;
        for(var i=0;i<childs.length;i++){
            z=childs[i].childNodes;
            adChilds(z,childs,oNode);


            function adChilds(a,b,c){
                if(a[i].hasChildNodes()){
                    adNode(b[i].nodeName,c);
                    var oNode_ch=oNode1;
                    for(var j=0;j<a.length;j++){
                        child1=a[j].childNodes;
                        adNode(child1[0].nodeValue,oNode_ch);
                    }
                }
                else{adNode(a[0].nodeValue,oNode);}
            }
        }

error is pointing at this line.

if(a[i].hasChildNodes()){

Can anyone suggest me where am I going wrong.

Thanks in advance!

Answers:

Answer

You're doing this:

z=childs[i].childNodes;

then, in the first line of adChilds(z,childs,oNode);, you're doing this:

if(a[i].hasChildNodes()){

But, i isn't an index into the children of a. It's an index into the parent's of a's children. Thus, if the parent of a doesn't have the same number of children as a has children, you will go out of index.

I don't know exactly what you're trying to accomplish in adChilds() so I'm not sure what fix to suggest, but I presume you that if you want to deal with the children of a, you should get the number of children of a and make sure you only access the number that actually exist


Some coding suggestions:

  1. I'd strongly suggest you use real variable names. Names like a, b, c and z for intermediate variables are cryptic and make your code hard to read.

  2. All local variables should be preceded with var at first definition (or defined at the top of the function), otherwise they become global variables which is asking for trouble, especially with asynchronous callback functions.

  3. When you see errors that aren't obvious to you upon first inspection of your code, then set a breakpoint in your favorite debugger and step through the code and examine the state of the variables to see exactly why you're getting the error. If you don't know how to use a debugger, learn. They are built into most browsers, easy and absolutely essential to efficient debugging.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.