Search code examples
javascripttimertypeerrorcountdowninnertext

Uncaught TypeError: Cannot set property 'innerText' of null - For Countdown Script


I am getting Uncaught TypeError: Cannot set property 'innerText' of null error message in my console where the errors just keep rising indefinitely. It is related to a script I have running to countdown to a particular set of dates.

I have attempted removing the script which removes the error. Aside from that I am not sure exactly where it's going wrong. Aside from something to do with the target.innerText = "Expired" line.

"use strict";

timer = function timer(target, date) {
  var target = document.querySelector(target);
  var countDownDate = new Date(date).getTime();
  setInterval(function () {
    var now = new Date().getTime();
    var distance = countDownDate - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor(distance % (1000 * 60 * 60 * 24) / (1000 * 60 * 60));
    var minutes = Math.floor(distance % (1000 * 60 * 60) / (1000 * 60));
    var seconds = Math.floor(distance % (1000 * 60) / 1000);
    target.innerText = days;

    if (distance < 0) {
      target.innerText = "Expired";
     }
  }, 1000);
};

timer("#timer1", "Jan 01, 2019 11:59:59");
timer("#timer2", "Jan 02, 2019 11:59:59");
timer("#timer3", "Jan 03, 2019 11:59:59");

Any and all help and suggestions would be appreciated.

Thank you

edit:

Here is a section of the html

<div class="container">
 <div class="dates-container">
  <div class="dates-wrapper">
    <p class="date"><strong>Jan 01</strong> <span class="days-remaining"><span id="timer1"></span> Days Remaining</span></p>
    <div class="divider"></div>
  </div>
  <div class="upcoming-dates">
   <p class="date"><strong>Jan 02</strong> <span class="days-rem"> . <span id="timer2"></span> Days Remaining</span></p>
   <div class="divider"></div>
  </div>               
 </div>
</div>

It works on the main index.html and I am trying to add the countdowns to a different page by giving the elements and ID of "timerX" - the errors didnt show up until I added the countdowns to the second page.

Thanks again for the help, I feel like I am overlooking something simple but I dont know.


Solution

  • The line

    var target = document.querySelector(target);
    

    is definitely setting var target to null. So that`s exactly what the interpreter is telling you.

    I assume it can't find #timer3.