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
7 Answers
Reset to default 12Make 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>©2016 School Apps. All Rights Reserved.</p>
To show 2016 dynamically we use that code