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.
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") ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With