- 2074 Chaitra · 2+3 marks
JavaScript DOM and date-time function
Short answer
The DOM is a tree of objects with window at the top and document containing all page elements. A JavaScript function using new Date(), getElementById().innerHTML, and console.log can display date and time in the page and console, updating with setInterval.
Explain JavaScript DOM model. Make use of JavaScript function to display the date and time in either HTML document or console.
JavaScript DOM model
The DOM represents the web page as a tree of objects. The top object is window, which contains document (the page), location, history, navigator. Under document are html, head, body and all elements, each a node object with properties (innerHTML, style, id) and methods (appendChild, setAttribute). JavaScript uses these objects to find elements (getElementById), change content and style, add or delete nodes and respond to events, so the page changes without reloading.
window
|-- document
| |-- html -- head, body -- elements -- text
|-- location
|-- history
Displaying date and time using JavaScript
The built-in Date object gives the current date and time.
<!DOCTYPE html>
<html>
<head><title>Date and Time</title></head>
<body>
<h3>Current date and time</h3>
<p id="dt"></p>
<script>
function showTime() {
var now = new Date(); // current date and time
var date = now.getFullYear() + "-" +
(now.getMonth() + 1) + "-" + now.getDate();
var time = now.getHours() + ":" +
now.getMinutes() + ":" + now.getSeconds();
// display in HTML document through DOM
document.getElementById("dt").innerHTML = date + " " + time;
// display in console
console.log("Date: " + date + " Time: " + time);
}
showTime();
setInterval(showTime, 1000); // update every second
</script>
</body>
</html>
Here getElementById("dt").innerHTML writes into the DOM, and console.log writes to the browser console. now.toLocaleString() is a shorter way to get a formatted string.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Document Object Model with HTML/JavaScript · Web Technology, chapter 4 · asked 2×
- JavaScript and significance of DOM · Web Technology, chapter 4