Solved

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

Posted on 2014-04-10
1
7,622 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
This article discusses how to implement server side field validation and display customized error messages to the client.
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…

717 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