How to dynamically update the copyright year in HTML

·

2 min read

Have you ever visited a website and noticed that the copyright year is still stuck in the past? It could be an oversight, but it can make the website appear outdated and unprofessional.

Fortunately, there's an easy way to avoid this issue by using JavaScript to generate the current year dynamically on a web page. In this article, we'll show you how to use JavaScript to generate a dynamic copyright year and keep your website up-to-date. So, if you want to ensure that your website looks professional and current, read on to learn how to automate this process with just a few lines of code.


<body>

    <footer id="footer">
        <p>Copyright &copy; <span id="copyrightYear"></span></p>
    </footer>

    <!-- Scripts -->
    <script>
        // Get the current year
        const currentYear = new Date().getFullYear();

        // Get the element with the id "copyrightYear"
        const yearElement = document.querySelector("#copyrightYear");

        // Insert the current year into the yearElement
        yearElement.innerHTML = currentYear;
    </script>
</body>

I've also seen people use document.write() to generate the dynamic copyright year, but from what I've learned, we should be very careful when using this function. Misusing it could lead to unintended changes to the entire page. It seems safer to select the element in the DOM and change its innerHTML property instead.

We are now in January 2023, let's make sure none of our sites stay in the year 2022, or ever gets outdated.