Cannot read property *0* of null

前端 未结 4 1591
长发绾君心
长发绾君心 2021-01-13 08:22

I get this error \"Cannot read property \'0\' of null.\"

I have a table with

somename.html

相关标签:
4条回答
  • 2021-01-13 08:48

    When you call setInterval, you must supply a function. You're calling the function immediately, not passing the function to setInterval. It should be:

    setInterval(test, 1000);
    

    Since you're calling it immediately, it's running before the DOM has loaded fully, and the td1 element isn't found. So getElementById returns null instead of the element.

    In addition, as the other answers pointed out, you should not use [0] to access the element returned by getElementById. It returns a single element, not a NodeList.

    0 讨论(0)
  • 2021-01-13 09:00

    if your id is unique then this will work

    document.getElementById('td1').style.color = 'blue';
    
    0 讨论(0)
  • 2021-01-13 09:00

    document.getElementById('td1') returns you the element, and not an array. Remove the [0].

    You could also perform a check on whether the element exists before trying to use it:

    function test() {  
        var elem = document.getElementById('td1');
        if(typeof elem == 'undefined') return;
    
        var date = new Date();
        if(date.getDay()==1 && date.getHours() >=13  && date.getMinutes() >=3 ) { //8-9AM  
            elem.style.color = 'blue';  
        } else if(date.getDay()==1 && date.getHours() == 14  && date.getMinutes() <= 20) {  
            elem.style.color = 'blue';  
        } else {  
          //nothing  
        }  
    }  
    setInterval(test, 1000);
    
    0 讨论(0)
  • 2021-01-13 09:06

    getElementById returns null if there is no match in the document. (Which then leads to exactly your error message).

    This means that either you have a typo in your selector or the html or the js gets executed before your element is included into the dom.

    Also, getElementById returns a single element and not an array (Node List to be precise), so the correct call would be:

    document.getElementById('td1').style.color = 'blue';
    

    Third problem:

    setInterval(test(),1000);
    //              /\
    // this will immeditately execute the function and
    // hands over the *return value* to setInterval
    

    will not work as intended, it needs to be

    setInterval(test,1000);
    //            /\
    // hand over the *function reference* to be executed after 1 second
    
    0 讨论(0)
提交回复
热议问题