Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  162] [ 7]  / answers: 1 / hits: 30780  / 10 Years ago, wed, april 2, 2014, 12:00:00

Keep getting this error, no idea why



Uncaught TypeError: Cannot read property 'innerHTML' of null



My code is:



function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}

function calculateCircumference (diameter) {
return diameter * 3.14;
}

write (calculateCircumference(4));

More From » innerhtml

 Answers
18

Admittedly, the error message is not exactly transparent as to its meaning (but at least you get an error - jQuery would just silently do nothing!)



What it means is that the result of document.getElementById('message') is null. Looking at the docs you will find that this happens when the element cannot be found.



The main reason for an element not being found is because it doesn't exist yet.



<script>// do something with document.getElementById('message');</script>
<div id=message></div>


The above will FAIL because message does not exist yet. Moving the script after the div will make it work.



Side-note: 3.14 is far too inaccurate. Use Math.PI instead, it's as accurate as a number in JavaScript can be.


[#71653] Tuesday, April 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
americar

Total Points: 631
Total Questions: 107
Total Answers: 103

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;