Unable to read property * 0 * of zero

I get this error "Can't read property" 0 "from null."

I have a table with

somename.html

<table>  
    <tr>  
    <td id="td1">text</td>  
    </tr>  
    </table>

somename.js

function test(){  
    var date=new Date();  
    if(date.getDay()==1 && date.getHours() >=13  && date.getMinutes() >=3 ){ //8-9AM  
        document.getElementById('td1')[0].style.color = 'blue';  
    }else if(date.getDay()==1 && date.getHours() == 14  && date.getMinutes() <= 20){  
            document.getElementById('td1')[0].style.color = 'blue';  
    }else{  
      //nothing  
    }  
}  
setInterval(test(),1000);

EDIT: new error if I delete [0] "Unable to read property of style 'null'

+4
source share
4 answers

getElementByIdreturns nullif there is no match in the document. (Which leads to an accurate error message).

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

In addition, it getElementByIdreturns a single element, not an array ( Node Listto be precise), so the correct call would be:

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

The third problem:

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

,

setInterval(test,1000);
//            /\
// hand over the *function reference* to be executed after 1 second
+6

document.getElementById('td1') , . [0].

, :

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

id ,

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

setInterval, . , setInterval. :

setInterval(test, 1000);

, DOM, td1 . getElementById null .

Also, as pointed out in other answers, you should not use [0]to access the item returned getElementById. It returns one element, not NodeList.

0
source

Source: https://habr.com/ru/post/1525049/


All Articles