Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  91] [ 1]  / answers: 1 / hits: 48515  / 11 Years ago, mon, february 3, 2014, 12:00:00

I get this error Cannot read property '0' of 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 remove [0] Cannot read property 'style' of null


More From » javascript

 Answers
49

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

[#72764] Sunday, February 2, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;