At the time of running var a = document.getElementById('test').innerHTML = toD(15); in your script <p id='test'> </p> does not exist.
place the script AFTER <p id='test'> </p> or wrap the entire script in its own function and assign it to onload so that it is only ran after <p id='test'> </p> and the rest of the DOM is available.
Either
<html>
<head>
</head>
<body>
<p id='test'> </p>
<script>
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
</script>
</body>
</html>
OR
<html>
<head>
</head>
<body>
<script>
window.onload = function() {
function toD(angle) {
return angle * (180 / Math.PI);
}
var a = document.getElementById('test').innerHTML = toD(15);
}
</script>
<p id='test'> </p>
</body>
</html>
Note: this is a very dirty way of using window.onload, that should only be used if this is to be the only script on the page that requires onload. For more information about using onload properly when there will be multiple scripts using it, please read How to Use window.onload the Right Way
tag
– Ghazanfar Mir Aug 12 '13 at 13:00