Dynamic JavaScript Code for Displaying Recent Years

We aim to generate a list of years dynamically, starting from the current year and going back to three years ago. This list will be useful for various scenarios, such as filtering data, selecting dates, or providing navigation options.

To display a list of years from the current year down to the last three years, you would need to adjust the parameters passed to the 'generateYearList' function.

CODE:

const currentYear = new Date().getFullYear();
//Here Date() object to create a new date instance representing the current date and time. 
const yearList = document.getElementById('year-list');
//This line retrieves a reference to an HTML element with the ID 'year-list'

function generateYearList(startYear, endYear) {
    for (let year = startYear; year >= endYear; year--) {
        const listItem = document.createElement('li');
        listItem.setAttribute('data-value', year);
        listItem.innerHTML = `<a href="#">${year}</a>`;
        yearList.appendChild(listItem);
    }
}


// Display the list of years from the current year to the last three years
generateYearList(currentYear, currentYear - 3);

we're calling the generateYearList function with currentYear as the starting year and currentYear - 3 as the ending year. This will generate a list of years from the current year down to the year three years prior to the current year and append it to the yearList element.

Sign In or Register to comment.