How To Use HTML DOM Time Object In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 05-10-2020

In Java script we can create Time on click of button .so today we are going to discuss how to use HTML DOM Time Object.

How To Use HTML DOM Time Object In JavaScript With Example

Time Object

The Time object represents an HTML <time> element.

Access a Time Object

You can access a <time> element by using getElementById():

Example(1)

<h2>I have a date on <time id="Time" datetime="2014-10-02">Gandhi Jayanti</time>.</h2>
<button class="btn btn-success" onclick="Get_time()">Click it</button>
<h2 id="demo"></h2>
<script>
    function Get_time() {
        var x = document.getElementById("Time").innerHTML;
        document.getElementById("demo").innerHTML = x;
    }
</script>

In above example when we click the button it will get the HTML content of the time element .


Create a Time Object

You can create a <time> element by using the document.createElement() method:

Example(2)

<button class="btn btn-success" onclick="get_time()">Click it</button>

<script>
    function get_time() {
        var x = document.createElement("TIME");
        x.setAttribute("datetime", "2014-10-02");
        var t = document.createTextNode("Gandhi Jayanti");
        x.appendChild(t);
        document.body.appendChild(x);
    }
</script>


In above example when we click button it will create a TIME element that specifies the date of "Gandhi Jayanti (2014-10-02)".

Time Object Properties
 

Property Description
dateTime Sets or returns the value of the datetime attribute in a <time> element


Complete Code For HTML DOM Time Object In JavaScript 
<!DOCTYPE html>
<html>
<head>
    <title>How To Use HTML DOM Time Object In JavaScript With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    h1{
        color:red;
    }
</style>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>How To Use HTML DOM Time Object In JavaScript With Example</h1>
    </div>
    <br>
        <div class="well">
            <h3>A demonstration of how to access a TIME element</h3>
            <h2>I have a date on <time id="Time" datetime="2014-10-02">Gandhi Jayanti</time>.</h2>
            <button class="btn btn-success" onclick="Get_time()">Click it</button>
            <h2 id="demo"></h2>
            <script>
                function Get_time() {
                    var x = document.getElementById("Time").innerHTML;
                    document.getElementById("demo").innerHTML = x;
                }
            </script>
        </div>
    <div>
</body>
</html>

Related Post