0

I've been trying for hours, just trying to figure out, how to fix a problem. And it's a script to include html with an id of "incl" and a custom attribute called "file" in javascript. And it's returning

"Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLHttpRequest.xhttp.onreadystatechange (includer.js:13)"

my script is:

var all = document.getElementsByTagName("*");
var fle = [];
var Incl = [];
var nIncl = [];
var xhttp = new XMLHttpRequest();
for (var i = 0, max = all.length; i < max; i++) {
  Incl[i] = all[i].getAttribute("id");
  if (Incl[i] == "incl") {
    nIncl[i] = all[i].getAttribute("id");
    fle[i] = all[i].getAttribute("file");
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById(nIncl[i]).innerHTML = this.responseText;
      }
    };
    xhttp.open("GET", fle[i], true);
    xhttp.send();
  }
}
<head id='incl' file="header.html"></head>

<body>
  <div id="incl" file="Navlist.txt"></div>
</body>
Skully Kra
  • 41
  • 1
  • 3
  • If you've been trying for hours, how have you been going about debugging this? –  Dec 20 '16 at 17:06
  • 1
    You're using the `id` attribute incorrectly. From [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id): "The id global attribute defines a unique identifier (ID) **which must be unique in the whole document.**" – p.s.w.g Dec 20 '16 at 17:07
  • 1
    In onreadystatechange, nIncl[i] will refer to the last i set by the for() loop, you've got a scoping problem in top of everything else – Micaël Félix Dec 20 '16 at 17:07
  • FWIW, [here's a rewrite](https://jsfiddle.net/emr70anm/) of your code that's less verbose and solves the scoping problem of the `i` variable. While the duplicate `id` attributes are an issue and should be corrected, you can close directly over the element instead of `i` so that you're not having to fetch by ID at all. –  Dec 20 '16 at 17:13
  • Your debugging efforts should include at a minimum using `console.log()` to verify the values of the variables that are at the center of the issue. Because you're having trouble fetching by ID, then it would make sense to log the values of `i` and `nIncl[i]` at the point where the DOM selection is being performed. –  Dec 20 '16 at 17:14
  • Here's a more moder approach: https://jsfiddle.net/emr70anm/1/ –  Dec 20 '16 at 17:21

0 Answers0