trying to build a javascript shopping cart. I have an event listener that is triggered when clicking on any item on the page. I am creating HTML (createElement('div')) that is generated by javascript upon clicking on a new, unique item that is not currently in the cart. I have an innerHTML attached to the 'div' that shows the contents of the item being inserted in the dropdown of the dom. When trying to add the content of the div in my if/else statement, i am left with a 'Uncaught TypeError: Cannot set property 'textContent' of null'.
Why is this happening? is my createElement('div') not rendering somehow? Any idea on how to get this to work, i am talking specifically about the content in my 'else' portion of the if/else conditional i have at the end of the code.
//dropdown menu hidden
const cartDropdown = document.querySelector('.cart-dropDown-items');
//every single + symbol
const addToCartButtons = document.querySelectorAll('.addToCart');
//name of item
const foodNames = document.querySelectorAll('.selection-row-foodName');
//price of item
const foodPrices = document.querySelectorAll('.selection-row-title');
//weight of item
const foodWeights = document.querySelectorAll('.selection-row-weight');
const items = [];
let total = 0;
// newItem - item added to dropdown when addToCart button is clicked on
const newItem = document.createElement('div');
newItem.className = 'dropDown-item';
newItem.innerHTML =
`<div class='dropDown-title dropDown-info'>
</div>
<div class='dropDown-amount dropDown-info'>
<p class='amount-items'></p>
</div>
<div class='dropDown-price dropDown-info'>
</div>`;
const title = document.querySelector('.dropDown-title');
const amount = document.querySelector('.dropDown-amount');
const price = document.querySelector('.dropDown-price');
for (let i=0; i<addToCartButtons.length; i++) {
addToCartButtons[i].addEventListener('click', function() {
//if item in 'Items' array
if (items.includes(addToCartButtons[i].value)) {
items.push(addToCartButtons[i].value);
} else { // if item is NOT in 'Items' array
items.push(addToCartButtons[i].value);
title.textContent = foodNames[i].textContent;
amount.textContent = '1';
price.textContent = foodPrices[i].textContent;
cartDropdown.appendChild(newItem);
}
})
}
<!--cart dropDown-->
<div class='cart-dropDown'>
<div class='cart-dropDown-header'>
<p>My Carts</p>
<p>Personal Cart</p>
<p class='cart-dropDown-close'>Close</p>
</div>
<div class='cart-dropDown-items'>
<!--
<div class='dropDown-item'>
<div class='dropDown-title dropDown-info'>Mixed bell pepper, 6 ct</div>
<div class='dropDown-amount dropDown-info'>1</div>
<div class='dropDown-price dropDown-info'>$9.84</div>
</div>
next unique item...
-->
</div>
<div class='cart-dropDown-checkout'>
<div class='cart-dropDown-checkout1'>
<p>Go to Checkout</p>
</div>
<div class='cart-dropDown-checkout2'>
<p>$0</p>
</div>
</div>
</div>