I have been attempting to make the following code snippet display the current date and time in a web browser. I saved the file as "date-time.js" using UTF-8 encoding.
I have tested it on various browsers such as Firefox, Chrome, and Edge,
// Execute this script after the page has loaded
window.onload = insertDateTime;
// Function to insert the current date and time
function insertDateTime() {
// Check if the browser supports DOM
if (!document.getElementById) return;
if (!document.createTextNode) return;
// Create a Date-Time object
var currentDate = new Date();
// Get the current date and time as a string
var dateTimeString = currentDate.toLocaleString();
// Select the target element where date-time needs to be inserted
var targetElement = document.getElementById('output');
// Ensure that the target exists
if (!targetElement) return;
// Clear the target element
while (targetElement.firstChild) {
targetElement.removeChild(targetElement.firstChild);
}
// Create a new text node with the current date-time
var newText = document.createTextNode(dateTimeString);
// Insert the new text into the target span
targetElement.appendChild(newText);
}
However, when I run the page in a browser, it fails to display the current date and time.