-1

I want to create two similar tables and do different things to them so I created two handlebars templates, each with their own script id to distinguish between them. I'm also fetching data from a db to fill in the template, and have two handlebars functions that are identical besides the function name and their respective script ids

If I only call one of the tables, it works fine, but when I call both, I get an error saying "Uncaught (in promise) TypeError: Cannot read property 'textContent' of null" and points to the "documentGetElementById" line of the second function, regardless of what order the functions are in.

Why might this be and how do I fix it? It seems like once the first function is read, it ignores the second or something which is why getElementById can't find anything?

HTML:

<div class="topScores">
 <script id="top-scores" type="text/x-handlebars-template">
  <table>
   ...
  </table>
 </script>
</div>

<div class="recentScores">
 <script id="recent-scores" type="text/x-handlebars-template">
  <table>
   ...
  </table>
 </script>
</div>

JS:

function listTopScores(id, scores){
    let target = document.getElementById(id);
    let template = Handlebars.compile(document.getElementById("top-scores").textContent);
    let content = template({'scores', scores});
    target.innerHTML = content;
}

function listRecentScores(id, scores){
    let target = document.getElementById(id);
    let template = Handlebars.compile(document.getElementById("recent-scores").textContent);
    let content = template({'scores', scores});
    target.innerHTML = content;
}

function loadScores(){
  fetch('js/scores.json')
  .then(response) => {
    return response.json()
   })
  then((data) => {
    listTopScores("content", data);
    listRecentScores("content", data);
  })
}

window.onload = function() {
    loadScores();
}
Lev Min
  • 1
  • 1
  • You're missing a quote after `id="top-scores` and `id="recent-scores`. – Ivar May 04 '21 at 09:29
  • ...and so you don't have elements with those `id` values, which is the **only** reason `getElementById` will ever return `null`. – T.J. Crowder May 04 '21 at 09:30
  • That was a mistake in the post, hard to see without the fonts of a code editor. With the quotes it doesn't work. If a quotation mark for both ids were missing, neither would show up, wouldn't it? But it does work, only for the first table – Lev Min May 04 '21 at 09:44
  • As the duplicate (and T.J. Crowder) explains, `document.getElementById()` only returns `null` if it can't find the element at the moment it is being executed. Make sure that the id's are are the same and in case the script tags are loaded dynamically, make sure to execute the script _after_ it has been inserted into the page. Running a stripped version [works fine](https://jsfiddle.net/nmzag4sw/). – Ivar May 04 '21 at 09:55

0 Answers0