最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Insert current year into HTML - Stack Overflow

programmeradmin1浏览0评论

I am using javaScript that detects the current year, and then wish to inset this into the HTML. I have the following but it seems to be undefined.

Here is my code...

HTML

<p>this year is <span id="year"></span></p>

JavaScript

var date = document.write(new Date().getFullYear());
document.getElementById("year").innerHTML = date;

I can do this in jQuery but I am trying to do this in vanailla javaScript, learning at the same time.

Thanks in advance.

I am using javaScript that detects the current year, and then wish to inset this into the HTML. I have the following but it seems to be undefined.

Here is my code...

HTML

<p>this year is <span id="year"></span></p>

JavaScript

var date = document.write(new Date().getFullYear());
document.getElementById("year").innerHTML = date;

I can do this in jQuery but I am trying to do this in vanailla javaScript, learning at the same time.

Thanks in advance.

Share Improve this question edited Oct 24, 2021 at 16:49 Roko C. Buljan 206k41 gold badges327 silver badges335 bronze badges asked Feb 20, 2015 at 10:44 AdamAdam 1,4598 gold badges29 silver badges48 bronze badges 1
  • n.b. This will be the year according to the system clock on the browsing machine, and not necessarily the year that the server believes it is – paul Commented Feb 20, 2015 at 10:49
Add a comment  | 

7 Answers 7

Reset to default 12

Make sure your element is read and ready to be manipulated: Also fix your JS:

<p>Year: <span id="year"></span></p>
        
<!-- JS right before the closing </body> tag -->
<script>
document.querySelector("#year").textContent = new Date().getFullYear();
</script>

Note that if one's computer clock is off, JavaScript might not be the right choice, in such case you can get the date from the backend.
If you use PHP:

<p>Year <span id="year"><?php echo date("Y"); ?></span></p>

in short:

<?= date("Y") ?>

Would it not be simpler and more efficient to simply do this in-line?

<p>this year is <script>document.write(new Date().getFullYear());</script>.</p>
<script>
window.onload = function(){
var date = new Date().getFullYear();
document.getElementById("year").innerHTML = date;
}
</script>
<p>this year is <span id="year"></span></p>
var date = (new Date()).getFullYear();

document.getElementById("year").innerHTML = date;

The problem is the document.write call. Try this:

var date = new Date().getFullYear();
document.getElementById("year").innerHTML = date;

This Javascript should work:

var date = (new Date().getFullYear()).toString();
document.getElementById("year").innerHTML = date;

to show date dynamically

<%=DateTime.Now.Year %>
<p>&copy;2016 School Apps. All Rights Reserved.</p>

To show 2016 dynamically we use that code

发布评论

评论列表(0)

  1. 暂无评论