Solved

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

Posted on 2014-04-10
1
7,097 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

707 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now