Я пытаюсь изменить цвет названия продукта (объекта) на основе текущего года. Я имею в виду, если год продукта совпадает с текущим годом, он должен изменить цвет заголовка. Всякий раз, когда я сохраняю, я получаю сообщение об ошибке в DevTools: «Uncaught TypeError: Невозможно установить свойство 'color' of undefined".
<form id="theForm">
<div>
<input type="text" id="title" placeholder="Type title...">
</div>
<div>
<input type="date" id="date">
</div>
<button type="submit" id="sub">Add</button>
</form>
<section class="result">
<div id="addedProducts"></div>
</section>
const theForm = document.getElementById("theForm", saveProduct);
theForm.addEventListener("submit", saveProduct);
function saveProduct(evt){
let proTitle = document.getElementById("title").value;
let proDate = document.getElementById("date").value;
const product = {
title: proTitle,
date: proDate
}
if(localStorage.getItem("products") === null){
const products = []; //initialized
products.push(product);// add a new Product
//to local localStorage
localStorage.setItem("products", JSON.stringify(products));
} else {
// get products from localStorage
const products = JSON.parse(localStorage.getItem("products"));
// add product to products
products.push(product);
// set again to localStorage
localStorage.setItem("products", JSON.stringify(products));
}
theForm.reset();
fetchProducts();
evt.preventDefault()
}
function fetchProducts(){
const products = JSON.parse(localStorage.getItem("products"));
const addedProducts = document.getElementById("addedProducts");
addedProducts.innerHTML = "";
products.forEach(addProduct);
function addProduct(product) {
const title = product.title;
const date = product.date;
const splitDate = date.split("");
const splittedYear = splitDate.slice(0, 4);
const splittedMonth = splitDate.slice(5, 7);
const splittedDay = splitDate.slice(8);
const jYear = splittedYear.join("");
const jMonth = splittedMonth.join("");
const jDay = splittedDay.join("");
const jDate = jMonth +"/"+ jDay +"/"+
jYear;
// Parsed Date attributes
const pYear = parseInt(jYear, 10);
const pMonth = parseInt(jMonth, 10);
const pDay = parseInt(jDay, 10);
// current Date
const cDate = new Date();
const cDay = cDate.getDate();
const cMonth = cDate.getMonth() + 1;
const cYear = cDate.getFullYear();
//Here's the problem!!!
if(pYear == cYear){
// The next line broke every thing
/* Uncaught TypeError: Cannot
set property 'color' of undefined*/
title.style.color = "#159";
console.log("yes");//that works fine
} else {
console.log("not");// So da that one
}
addedProducts.innerHTML += '<div class="res">'+
'<span class="title">' + title +'</span>' +
" " + '<span class="dateClass">' + jDate +'</span>'+
'<button onclick="deletePro(\'' + title + '\',\'' + date + '\')" id="remove">Delete</button>' +
'</div>';
}
}
Извините, если это длинный код. Я был так смущен!