Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert current year into HTML

Tags:

javascript

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.

like image 705
Adam Avatar asked Oct 15 '25 16:10

Adam


1 Answers

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") ?>
like image 86
Roko C. Buljan Avatar answered Oct 17 '25 06:10

Roko C. Buljan