简体   繁体   中英

Error trying to change innerHTML — Cannot set property 'innerHTML' of null

I am trying to change the innerHTML of a div based on the number populated by a javascript function. Unfortunately I am getting an error and I am unsure why.

Pseudocode

If number > 2 change innerHTML to seconds otherwise change to second .

I had a look around and I found something related to the function being triggered before the DOM. I did some changes but still no success. What I am doing wrong? How can I make trigger the function after the DOM being rendered? Isn't the window.onload already doing the work?

Thank you in advance

JS

$(document).ready(function() {
  window.onload = function() {
    // Month,Day,Year,Hour,Minute,Second
    upTime('may,05,2006,00:00:00');
  };

  function upTime(countTo) {
      var now = new Date();
      countTo = new Date(countTo);
      var difference = (now - countTo);

      var years = Math.floor(difference / (60 * 60 * 1000 * 24) / 365);
      var days = Math.floor(difference / (60 * 60 * 1000 * 24) * 1);
      var hours = Math.floor((difference % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
      var mins = Math.floor(((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
      var secs = Math.floor((((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);

      document.getElementById('years').firstChild.nodeValue = years;
      document.getElementById('days').firstChild.nodeValue = days;
      document.getElementById('hours').firstChild.nodeValue = hours;
      document.getElementById('minutes').firstChild.nodeValue = mins;
      document.getElementById('seconds').firstChild.nodeValue = secs;

      if (secs > 2) {
        console.log('over');
        document.getElementById('.seconds').innerHTML = "seconds";
      } else {
        console.log('lower');
        document.getElementById('.seconds').innerHTML = "second";
      }

      clearTimeout(upTime.to);
      upTime.to = setTimeout(function() {
          upTime(countTo);
      }, 1000);
  }
});

Get element by class : document.getElementsByClassName('seconds') and by Id document.getElementById('seconds')

But with jQuery, id $('#seconds') and class $('.seconds')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM