0

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 
nosh
  • 620
  • 3
  • 14
  • 50
  • 1
    This is a standard problem of nonscoped `var` variable inside a loop. You need to use `let` or simply replace the second `document.getElementById('i_frame'+i)` with `this`. – wOxxOm May 29 '19 at 05:27
  • using `this` works, but how can I use an array of values created outside the onload() function, inside the function? – nosh May 29 '19 at 13:00
  • I figured it out – nosh May 29 '19 at 16:15

0 Answers0