[英]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? 我想给
h1
元素文本(而不是输入文本)作为var unix timestamp的输入..有没有办法做到这一点?
You can give the h1
element an id
and use document.getElementById
to get the h1
element. 您可以给
h1
元素一个id
并使用document.getElementById
来获取h1
元素。 Then you can use .textContent
to get the text within the h1
tag. 然后,您可以使用
.textContent
来获取h1
标签内的文本。 Finally, you can use a +
to convert the string retrieved from textContent to a number. 最后,您可以使用
+
将从textContent检索的字符串转换为数字。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.