I am trying to create multiple iframes with urls of the same origin in a website and then loop through each iframe to access an element with the same id and currently have the element's innerHTML logged to the console. When I do this individually it works but when I try looping through the iframes I created, I get an error on the console. This for a chrome extension and I am running this through chrome.
Code:
var iframe;
  for (var i = 0; i < num_courses; i++) {
    iframe = document.createElement("iframe");
    iframe.setAttribute("src", links[i].href);
    iframe.id = "i_frame" + i;
    // iframe.height = 0;
    // iframe.width = 0;
    // iframe.style.border = "none";
    document.body.appendChild(iframe);
  }
  for (var i = 0; i < num_links; i++) {
    document.getElementById('i_frame' + i).onload = function() {
      var main = document.getElementById('i_frame' + i).contentDocument.getElementById('percentage').innerHTML;
      var percentages = main.match(/(\d|\.)+\%/g);
      console.log(percentages[0]);
    };
  }
The error occurs on the line:
var main = document.getElementById('i_frame' + i).contentDocument.getElementById('class_avg').innerHTML;"
Error:
Uncaught TypeError: Cannot read property 'contentDocument' of null
                    at HTMLIFrameElement.document.getElementById.onload 
