Home > database >  How do I fix currentDate and innerText JS not showing the date on my website?
How do I fix currentDate and innerText JS not showing the date on my website?

Time:02-03

I'm developing a calendar for my website which shows in the heading the month and the year. Everything seems to be working and I can't find any syntax errors. However, when I try to show the current month and year in the calendar it shows literally the innerText property (${months[currMonth]} ${currYear}) and not the results (in this case, February 2023). Can you help me figure out what's going on with my code?

Text shown instead of the month and year in the website

<main>
    <div >
        <header>
            <p ></p>
            <div >
                <span >chevron_left</span>
                <span >chevron_right</span>
            </div>
        </header>
</main>
const currentDate = document.querySelector(".current-date");

// getting new date, current year and month
let date = new Date(),
currYear = date.getFullYear(),
currMonth = date.getMonth();

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 
                'August', 'September', 'October', 'November', 'December'];

const renderCalendar = () => {
    currentDate.innerText = '${months[currMonth]} ${currYear}';
}

renderCalendar();

I tried looking for syntax errors and even asked some friends but they were not sure about what could be going wrong. I'm new to using js so I'm not an expert identifying errors. Any help would be very much appreciated.

CodePudding user response:

It seems that in your code, you are using a string literal ('), what you are looking for is a template literal (`) where the variables are actually replaced in the text.

You can use this to achieve what you want:

currentDate.innerText = `${months[currMonth]} ${currYear}`;

  • Related