Search code examples
javascriptjqueryhtmlcssweb3js

Selecting html elements text as input for JavaScript


var unixtime =356674566

var newDate = new Date();

newDate.setTime(unixtime * 1000);

dateString = newDate.toUTCString();

document.getElementById("time").innerHTML = dateString;

I wanted to give h1 element text(not input text) as an input to var unix timestamp..is there any way to do that?


Solution

  • You can give the h1 element an id and use document.getElementById to get the h1 element. Then you can use .textContent to get the text within the h1 tag. Finally, you can use a + to convert the string retrieved from textContent to a number.

    See working example below:

    document.addEventListener('DOMContentLoaded', function() {
      var unixtime = +document.getElementById('unix').textContent;
      var newDate = new Date();
    
      newDate.setTime(unixtime * 1000);
      dateString = newDate.toUTCString();
    
      document.getElementById("time").textContent = dateString;
    });
    <h1 id="unix">356674566</h1>
    <p>Date: <span id="time"></span></p>