Dynamically Update Footer Year in JavaScript Using Date Object

Answered using ChatGPT 4o by ChatGPT4o

Question:

A JavaScript, Dynamically Change "[Current Year]" with Current Year in Code Below: <footer class="center"> <h6 class="text-center">Copyright © [Current Year], Title.</h6> </footer>

Answer:

To dynamically change "[Current Year]" with the current year in your JavaScript code, you can use the Date object to get the current year and then update the content of the footer accordingly. Here's how you can do it:

  1. Add an id attribute to the <h6> element so you can easily target it with JavaScript.
  2. Use JavaScript to get the current year and update the content of the <h6> element.

Here's the updated HTML and JavaScript code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dynamic Year Example</title>
</head>
<body>
  <footer class="center">
    <h6 id="footer-text" class="text-center">Copyright &copy; [Current Year], Title.</h6>
  </footer>

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

    // Get the footer text element
    const footerText = document.getElementById('footer-text');

    // Update the footer text with the current year
    footerText.innerHTML = `Copyright &copy; ${currentYear}, Title.`;
  </script>
</body>
</html>

In this code:

  • The id="footer-text" attribute is added to the <h6> element to make it easy to select with JavaScript.
  • The JavaScript code gets the current year using new Date().getFullYear().
  • The innerHTML property of the footerText element is updated to include the current year.

This will ensure that the footer always displays the current year dynamically.