Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  183] [ 4]  / answers: 1 / hits: 34122  / 7 Years ago, wed, march 29, 2017, 12:00:00

I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:



Uncaught TypeError: Cannot read property 'append' of null at index.html:82



Here is the full page code:



<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>

<script>

function checkDistance(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}

function deg2rad(deg) {
return deg * (Math.PI/180)
}

var fixedlat = 51.714236;
var fixedlon = 50.710236;
var miles = 20;
var distanceLimit = miles * 1.6; //(km)
var data = [
{
name: Paul Brooks,
location: {
lat: 51.714236,
lon: 50.710236
}
},
{
name: Jason Orange,
location: {
lat: 52.030778298795856,
lon: 0.364888567109396
}
},
{
name: Mark Way,
location: {
lat: 53.41899784623413,
lon: -1.9138465628943413
}
},
{
name: Ben Bon,
location: {
lat: 52.30976192959104,
lon: -0.4014670363034498
}
},
{
name: Chris Col,
location: {
lat: 53.45301856182801,
lon: -1.8765834388107732
}
},
{
name: Von Van,
location: {
lat: 53.82771812914788,
lon: -0.7563793003592991
}
}
];

for(var i = 0;i < data.length;i++){

var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);

if(result <= distanceLimit){
var resultList = document.getElementById('resultList');
resultList.append(data[i].name + ', ');
}
}



</script>


</head>
<body>

<div id=resultList></div>

</body>
</html>


Why I'm I getting this error and how can I fix it?


More From » javascript

 Answers
5

Your javascript code executes even before the html is loaded, due to which it is unable to locate 'resultList' element.



Wrap your below code in some function.



function foo(){
for(var i = 0;i < data.length;i++){
var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);
if(result <= distanceLimit){
var resultList = document.getElementById('resultList');
resultList.append(data[i].name + ', ');
}
}
}


Now call this function through onload() event which will be executed only when whole page is loaded.



<body onload=foo()>
<div id=resultList></div>
</body>

[#58340] Monday, March 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;