Troubleshooting a Mystery JavaScript Reference Error in a Date and Time Application

Currently, I am working on developing a JavaScript file to create variables for dates and times using the shortcut method. Although everything seems to be in order from what I can see, it does not display correctly, and when checked with Google Chrome's debugger, it shows an error message:

[Uncaught TypeError: Cannot Read 'firstChild' of null]

This is the code snippet that I have written:

function mdy(){

    var
        h = new Date(),
        year = h.getFullYear(),
        month = h.getMonth() + 1,
        day = h.getDate();

        if(month < 10) { month = "0" + month; }

        if(day < 10) { month = "0" + month; }

        var string = month + "/" + day + "/" + year;

        document.getElementById('mdy').firstChild.nodeValue = string;

}

function ymd(){

    var
        h = new Date(),
        year = h.getFullYear(),
        month = h.getMonth() + 1,
        day = h.getDate();

        if(month < 10) { month = "0" + month; }

        if(day < 10) { month = "0" + month; }

        var string = year + "/" + month + "/" + day;

        document.getElementById('ymd').firstChild.nodeValue = string;

}

var $date = {

    mdy: '<span id="mdy">&nbsp;</span>',
    ymd: '<span id="ymd">&nbsp;</span>'

}

/* $time module */
// this comes in two formats, standard and military. 
// type $time.standard for standard time and $time.military
// for military time
function tstandard(){

    var
        h = new Date(),
        hours = h.getHours(),
        minutes = h.getMinutes();

        minutes = ( minutes < 10 ? "0" : "" ) + minutes;

        var diem = ( hours < 12 ) ? "am" : "pm";

        hours = ( hours > 12 ) ? hours - 12 : hours;

        hours = ( hours == 0 ) ? 12 : hours;

        var string = hours + ":" + minutes + " " + diem;

        document.getElementById("tstandard").firstChild.nodeValue = string;

}

function tmilitary() {

    var
        h = new Date(),
        hours = h.getHours(),
        minutes = h.getMinutes();

        minutes = ( minutes < 10 ? "0" : "" ) + minutes;

        hours = ( hours == 0 ) ? 12 : hours;

        if(hours < 10) { hours = "0" + hours }

        var string = hours + ":" + minutes;

        document.getElementById("tmilitary").firstChild.nodeValue = string;

}

var $time = {

    standard: "<span id='tstandard'>&nbsp;</span>",
    military: "<span id='tmilitary'>&nbsp;</span>"

}

/*! universal body onload function !*/
window.onload = function(){

    mdy(); setInterval('mdy()', 1000);
            ymd(); setInterval('ymd()', 1000);

    tstandard(); setInterval('tstandard()', 1000);
    tmilitary(); setInterval('tmilitary()', 1000);

} 

In my HTML file, I have included the following script:

<script>document.write($date.mdy + " - " + $time.standard);</script> 

Answer №1

You have created two placeholder elements in the DOM -

<span id="ymd"></span>
and <span id="tstandard">.

In the window.onload handler, you are attempting to update the content of these two placeholders as well as two other elements that are not part of the DOM (id="ymd" and id="tmilitary"). The calls to document.getElementById('ymd') (and 'tmilitary') result in undefined due to this reason.

The solution is to eliminate the calls to the ymd and tmilitary functions.

window.onload = function(){
  mdy();
  setInterval(mdy, 1000);

  tstandard();
  setInterval(tstandard, 1000);
};

I have also simplified the calls to setInterval for better efficiency and clarity by passing references instead.

Answer №2

Consider using the following:

document.getElementById('mdy').innerHTML = value;

or try this alternative:

document.getElementById('mdy').nodeValue = value;

as opposed to:

document.getElementById('mdy').firstChild.nodeValue = value;

This should resolve any issues. (No need to retrieve the firstChild when calling getElementById, as it already returns a node by default.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is jQuery AJAX returning improperly formatted JSON when using the jsonp type?

$('#rn_s').keyup(function() { var rn = $('#rn_s').val(); if(rn.length == 9) { $.ajax({ url: 'http://routingnumbers.info/api/data.json?rn=' + rn, type: 'GET', dataT ...

Look into HTML and JavaScript problems specific to IOS devices

I have encountered some HTML markup and JavaScript functionality issues on my web-app that seem to only occur on iPad and iPhone. Unfortunately, I do not have access to any iOS devices to debug these problems. How can I replicate and troubleshoot these i ...

Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to re ...

basic computation of whole and decimal values using jquery

I'm having trouble multiplying 2 values in my code where the quantity is an integer and credit price is a decimal number. However, when I run the script, nothing seems to happen. Can someone please help me identify and resolve this issue? Any insight ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

Pattern matching for traversing object properties

Is there a dependable method to match property-syntax using a Javascript regex? My goal is to identify whether a string contains a path structure, without the need to extract the specific members. For instance, if I have a string such as: someobject.somek ...

Creating a multilingual website with Nextjs 13 App Router using internalization, all without the need

As I develop a web app that requires user authentication to access, I am currently using Next.js 13 with the App Route (not Pages Route). My goal is to implement internationalization without having to create sub-routes like /en, or use domains such as mywe ...

Styling a dynamically-injected div using an AJAX request (xhrGet)

Hello everyone, currently I am using the code below to fetch updated content after receiving a "push" event from a server. The new content is then used to replace the existing div/content. However, I'm facing an issue where none of my styles from the ...

What is the best way to store an ES6 Map in local storage or another location for later use?

let map = new Map([[ 'a', 1 ]]); map.get('a') // 1 let storageData = JSON.stringify(map); // Saving in localStorage. // Later: let restoredMap = JSON.parse(storageData); restoredMap.get('a') // TypeError: undefined is not a ...

What is the best way to import information from a CSV or Excel file directly into my program?

I am currently using puppeteer for automating a form submission process. I am looking to extract data directly from a csv file and input it into the form. Can someone guide me on how to achieve this? The CSV file contains the following information: Fir ...

What is the best way to incorporate HTML and JavaScript into an Angular view?

Within my markup, there is a substantial chunk of code enclosed with ng-controller tags. The structure resembles this: <div ng-controller="MyController"> <script> // MyController is initialized with current_item_data to streamline ...

Interactive feature in Three.js causes page to scroll downwards upon object selection

Exploring Three.js for the first time, I'm looking to integrate it into the landing page of my website. However, I've encountered an issue where clicking on the scene area with my object causes the page to shift downward. I've tried adding o ...

Having Trouble Accessing Custom Screen in React Navigation?

The navigation from the Order screen to the Home Screen is not working as expected. Every screen in the route works, except for the Home screen, which just navigates back to the Map screen. I have clearly instructed to navigate to Home. Here is the curren ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

Code for Custom Controllers in Strapi Beta version 3.0

I have encountered some discrepancies in the beta version of Strapi's controllers compared to the previous version. The new version includes multipart/sanitization boilerplate, and I am having trouble integrating my order object and Stripe charge. Be ...

Implementing a redirect following the notification

I'm facing an issue with a function that sends form data to Google Sheets. How can I make the redirect button work after displaying an alert message? I attempted using window.location.href='', but it redirects without submitting the data. & ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...

I can't seem to get the post method to work properly for some unknown reason

Hello there, I am encountering an issue while trying to submit a form on my website using the post method. For some reason, it keeps returning a null value. However, when I send data not through the form but instead by reading axios, it works perfectly fin ...

Best practice for verifying if a form is empty in Ember.js

My form includes HTML5 validation implemented in the following way: <script type="text/x-handlebars" id="project"> <div class="row"> <div class="span6"> <div class="well well-small"> <p s ...

Accessing properties in JSON data with AngularJS

I am experiencing issues with accessing a JSON object returned from an $http call in my AngularJS app. I have provided the code snippet below, but it seems that nothing is being rendered on the HTML. Can anyone please assist me in identifying what I might ...