0

I tried looking at other threads with similar issues, but still can't seem to get this resolved.

Currently, I have a search bar that displays relevant results after the user hits a button. This works.

The user is then able to click on any one of the results and have it take them to a new HTML page. This also works.

I am trying to display a variable from the JS file on the HTML page, and I've tried using .innerHTML, but I keep getting the error:

onePage.js:61 Uncaught TypeError: Cannot set property 'innerHTML' of null

This is what I have in my HTML file:

   <div id="output"></div>

And this is what I have in my JS file:

function setList(group) {

  clearList();
   for (const state of group) {

      const item = document.createElement('li');
      item.classList.add('list-group-item');
      const text = document.createTextNode(state.name); 

   
      var newListItem = document.createElement("li");
      var newAnchor = document.createElement("a");
      newAnchor.textContent = state.name;
      document.getElementById("output").innerHTML = text; // line where I get error

     
      newAnchor.setAttribute('href', "displayInfo.html"); 
      newListItem.appendChild(newAnchor);

      list.appendChild(newListItem);
      console.log(newListItem);

   }

Can someone please help me out? Thanks in advance!

1 Answers1

1

If the file reference in the HTML is correct then it seems like your code is running before the DOM is loaded fully. You can try calling the function inside DOMContentLoaded:

window.addEventListener('DOMContentLoaded', (event) => {
  // call your function here
});
  • I tried adding the DOMContentLoaded like you suggested, but the text is not displaying. I added it inside the setList function. I also tried adding it when I actually call the setList function, but in that case, nothing happened at all (search bar stopped working too). I can update the original post for clarification if needed. window.addEventListener('DOMContentLoaded', (event) => { document.getElementById("output").innerHTML = text; }); – user14262940 Sep 28 '20 at 05:53
  • @user14262940, is there any error? – destiny awaits Sep 28 '20 at 05:54
  • No error when I added the addEventListener within the setList function, but no text is displaying in the HTML file – user14262940 Sep 28 '20 at 05:56
  • @user14262940, you should call the function `setList` inside the `DOMContentLoaded`, not the single line of code. – destiny awaits Sep 28 '20 at 06:00
  • I tried calling setList inside the DomContentLoaded, but my search bar comletely stopped working... apologizes for the confusion, I am new to JS – user14262940 Sep 28 '20 at 06:07