Solved

TypeError: document.getElementById(...) is null

Posted on 2014-04-10
1
7,365 Views
Last Modified: 2014-04-11
In the javascript console I get this error:

TypeError: document.getElementById(...) is null

How do I have to change this code to fix it? I think I have to do a NULL check but not sure how to do it.

  function computeTotalDistance(result) {
    var total = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
      total += myroute.legs[i].distance.value;
    }
    total = total / 1000.
    document.getElementById("total").innerHTML = total + " km";
  }   

Open in new window

0
Comment
Question by:seopti
1 Comment
 
LVL 38

Accepted Solution

by:
Tom Beck earned 500 total points
ID: 39993227
You could check for null and undefined...
var ele = document.getElementById("total");
  if(typeof ele !== 'undefined' && ele !== null) {
    document.getElementById("total").innerHTML = total + " km";
  }

Open in new window

...but if you know for sure that an element with that id is on the page, the more likely possibility for the error is that you are looking for the element before it exists on the page. For example, if your computeTotalDistance function is called from other code in the head section that runs automatically on window load.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question