Search code examples
javascriptxmlhttprequestgetelementsbytagnameonreadystatechange

loop doesn't work inside `onreadystatechange`


here is my code:

xmlhttp.onreadystatechange = function () {

              if (this.readyState == 4)

                  if( this.status == 200) {
                  response = xmlhttp.responseXML;
                  var channel = response.documentElement;
                  var title = channel.getElementsByTagName("title")[0].firstChild.nodeValue;

                  var parent =  document.getElementById("journalTitle");
                  parent.innerHTML = title;

                  var articleList = document.getElementById("articleList");

                  item = channel.getElementsByTagName("item");
                  var list = new Array();
                  itemSize = (channel.getElementsByTagName("item").length);
                  var i =0;
                  do{

                      list[i] = item[i].getElementsByTagName("title")[0].firstChild.nodeValue;

                      item = document.createElement("div");
                      item.innerHTML = list[i];
                      articleList.appendChild(item);
                      i++;


                  }while(i=itemSize);

                } 

the size variable is 22 and when I write alert(item[5].getElementsByTagName("title")[0].firstChild.nodeValue); it shows me the fifth element and so on, but inside the loop it just understand the first element of item for the rest it returns error :

Uncaught TypeError: Cannot call method 'getElementsByTagName' of undefined


Solution

  • I found my problem so ridiculous. although the while was incorrect, the for didn't work neither. the problem was that I have used different variables with the same name item . the problem was solved when I changed the code like so:

    xmlhttp.onreadystatechange = function () {
    
              if (this.readyState == 4)
    
                  if( this.status == 200) {
                  response = xmlhttp.responseXML;
                  var channel = response.documentElement;
                  var title = channel.getElementsByTagName("title")[0].firstChild.nodeValue;
    
                  var parent =  document.getElementById("journalTitle");
                  parent.innerHTML = title;
    
                  var articleList = document.getElementById("articleList");
    
                  item = channel.getElementsByTagName("item");
                  var list = new Array();
                  itemSize = (channel.getElementsByTagName("item").length);
    
                  for (i = 0;i<itemSize;i++){
    
                      list[i] = item[i].getElementsByTagName("title")[0].firstChild.nodeValue;
    
                      itemD = document.createElement("div");
                      itemD.innerHTML = list[i];
                      articleList.appendChild(itemD);
    
    
                  }
    
                } 
     }