0

When I am changing from one city to another my 5 day forcast stays and the next cities 5 day forcast addes to the list, which makes the list very long if you check weather in a few cities without reloading the page inbetween. What have I done wrong? https://unicornweather.netlify.app/

// FORECAST FOR 5 DAYS
const readForecast = (json) => {
    const forecastContainer = document.getElementById("forecast");
    const forecastContainer2 = document.getElementById("forecast2");

    // AT 00.00
    const filteredForecast = json.list.filter((item) =>
        item.dt_txt.includes("00:00:00")
    );
    filteredForecast.forEach((forecast) => {
        let forecastElement = document.createElement("div");
        let day = new Date(forecast.dt * 1000).getDay();
        const days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
        forecastElement.innerHTML = `
            <div class="forecastDays">${days[day]}</div>`;
        forecastElement.classList.add(`forecast1`);
        forecastContainer.appendChild(forecastElement);
    });

    const objectDate = {};

    json.list.forEach((item) => {
        const date = item.dt_txt.split(" ")[0];
        if (objectDate[date]) {
            objectDate[date].push(item);
        } else {
            objectDate[date] = [item];
        }
    });

    // AT 12.00
    const filteredForecastNoon = json.list.filter((item) =>
        item.dt_txt.includes("12:00:00"));
    filteredForecastNoon.forEach((forecast) => {
        let forecastElement = document.createElement("div");

        const date = forecast.dt_txt.split(" ")[0];
        const weatherData = objectDate[date];

        const temps = weatherData.map((value) => value.main.temp);
        
        const minTemp = Math.min(...temps);
        const maxTemp = Math.max(...temps);

        forecastElement.innerHTML = `
            <div class="forecastTemp">${minTemp.toFixed(
              0
            )}&#176c  /  ${maxTemp.toFixed(0)}&#176c</div>`;
        forecastElement.classList.add(`forecast2`);
        forecastContainer2.appendChild(forecastElement);
    });
}

enter image description here

  • 2
    I see appends to the forecast containers. I don't ever see removals. – Taplar Sep 25 '20 at 17:47
  • you need to add an id to the div you're adding, and then remove it before creating the next one. here is a reference https://stackoverflow.com/questions/3387427/remove-element-by-id – rhavelka Sep 25 '20 at 17:48

0 Answers0