Ritim İstanbul A5 Blok No: 46, D: 112, 34846 Maltepe/İstanbul

Automatically inserting current dates into HTML elements with JavaScript

In today’s blog post, we’re going to explore a useful JavaScript code snippet that allows you to automatically insert the current date into specific elements on your web page. Whether you’re managing a product catalog or any other list that requires up-to-date information, this script can be a valuable addition to your web development toolkit.

The output shows the current date in column 5.

Introduction: The Need for Current Dates

Imagine managing a product catalog on your website. You want your customers to know when product information was last updated. Manually updating the date for each product can be time-consuming and error-prone. Fortunately, JavaScript comes to the rescue. Let’s dive into how you can automate this process.

The HTML Structure

We start with an HTML table that displays product information. Each row represents a product, and we have columns for “Product Name,” “Price,” “Stock Status,” “Platform,” and “Last Updated.”

<!-- HTML table structure -->
<table>
    <thead>
        <tr>
            <th>Product Name</th>
            <th>Price</th>
            <th>Stock Status</th>
            <th>Platform</th>
            <th>Last Updated</th>
        </tr>
    </thead>
    <tbody>
        <!-- Product rows with placeholders for JavaScript-generated date -->
        <!-- ... -->
    </tbody>
</table>

Automating the Date Insertion

To automatically insert the current date into the “Last Updated” column, we use JavaScript. The script checks each row, and if the product has a “Last Updated” column, it populates it with the current date.

// JavaScript code for inserting the current date into the "Last Updated" column
const currentDate = new Date();
const day = currentDate.getDate().toString().padStart(2, '0');
const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
const year = currentDate.getFullYear();
const formattedDate = `${day}/${month}/${year}`;

const elements = document.querySelectorAll(".fb-product-prices-table");

elements.forEach((element) => {
    const lastUpdatedColumn = element.querySelector("td:last-child");

    if (lastUpdatedColumn) {
        lastUpdatedColumn.textContent = formattedDate;
    }
});

Output

Product Name Price Stock Status Platform Last Updated
Product 1 $19.99 In Stock Amazon
Product 2 $29.99 Out of Stock eBay
Product 3 $39.99 In Stock Allegro

Let’s break it down step by step:

  • Getting the Current Date:
  • We start by creating a new Date object named currentDate. This object represents the current date and time when the script is executed.
  • Formatting the Date:
  • Next, we extract the day, month, and year components from the currentDate object. These components are then converted to strings and formatted to always have two digits. This ensures that the date is displayed as “DD/MM/YYYY” format, even if the day or month is a single digit.
  • Selecting Elements with a Specific Class:
  • We use document.querySelectorAll(".fb-product-prices-table") to select all elements with the class “fb-product-prices-table.” These elements are assumed to represent individual product listings in the table.
  • Looping Through Elements:
  • We use a forEach loop to iterate through the selected elements, which represent individual product listings.
  • Locating the “Last Updated” Column:
  • For each product listing, we use element.querySelector("td:last-child") to find the last <td> element within that specific row. This effectively targets the “Last Updated” column in the table.
  • Updating the Column with Current Date:
  • If a “Last Updated” column exists in the row (as indicated by if (lastUpdatedColumn)), we set its textContent to the formattedDate. This action replaces the content of the “Last Updated” column with the current date in the “DD/MM/YYYY” format.

In summary, this JavaScript code automates the process of updating the “Last Updated” column for each product in the table with the current date. It does this by selecting the specific class, identifying the last column in each row, and updating its content with the formatted date. This dynamic approach ensures that your product listings always display the most recent update date.

Conclusion: Keeping Users Informed

By automating the insertion of the current date, you ensure that your customers always have access to the latest information. This not only enhances the user experience but also saves you time and effort in managing your product catalog.

JavaScript’s ability to manipulate the Document Object Model (DOM) empowers web developers to create dynamic and user-friendly websites. So, go ahead and implement this code to improve your product listings and keep your audience up to date.

We hope this guide helps you in your web development endeavors. Stay tuned for more insights and tips in our future blog posts.

More blogs

JavaScript var vs let variables: What’s the difference?

JavaScript is a popular and versatile programming language that powers many web applications. However, it also has some quirks and pitfalls that can confuse...

What ‘data’ element used for in HTML?

HTML is a markup language that allows us to create web pages with different types of content. However, not all content is equally understandable...

Is it possible to connect Google Sheets with JavaScript?

The fusion of web development and data management has become crucial for efficient workflow and innovative solutions. One such powerful combination is the integration...

How to add the current date automatically to HTML with JavaScript?

In web development, it's often necessary to display the current date on a webpage. Whether you're building a blog, an e-commerce site, or a...

What is Swiper JS and how to use it?

Swiper JS is a powerful and versatile library that allows you to create stunning and interactive web pages and apps with touch-friendly sliders, carousels,...

Splitting paragraphs into sentences in Google Sheets with a custom function

Google Sheets sometimes lacks the precise functions we require. However, the application offers a remedy in the form of "Apps Script," enabling the creation...

More from the blog

JavaScript var vs let variables: What’s the difference?

JavaScript is a popular and versatile programming language that powers many web applications. However, it also has some quirks and pitfalls that can confuse...

What ‘data’ element used for in HTML?

HTML is a markup language that allows us to create web pages with different types of content. However, not all content is equally understandable...

Is it possible to connect Google Sheets with JavaScript?

The fusion of web development and data management has become crucial for efficient workflow and innovative solutions. One such powerful combination is the integration...

How to add the current date automatically to HTML with JavaScript?

In web development, it's often necessary to display the current date on a webpage. Whether you're building a blog, an e-commerce site, or a...