I'm currently facing an issue while working on a school project. The problem arises with a textContent error when I attempt to import a JSON file and utilize the data in a foreach loop. Despite defining the properties with elements from the JSON file, I encounter a typeError: cannot set property 'textContent' of undefined.
If I remove the two lines containing textContent, the issue persists with the appendChild property, resulting in an error stating: cannot read property 'appendChild' of null.
Upon logging coffee.name in my forEach loop, I do receive the correct first name. However, it seems that the loop is unable to proceed further due to the errors occurring later in the code.
Below is my JavaScript code snippet:
import './style.css';
import data from './assets/data/coffees.json';
const init = () => {
console.log(data);
createPriceList(data);
};
const createPriceList = coffees => {
const ul = document.querySelector('prices__list');
console.log(coffees);
coffees.coffees.forEach(coffee => {
if (coffee.plantbased === true) {
const price = document.createElement('li');
price.classList.add('price');
const a = document.createElement('a').classList.add('price__button');
const spanWrapper = document.createElement('span').classList.add('price__button__wrapper');
const spanName = document.createElement('span').classList.add('price__button__name');
const spanAmount = document.createElement('span').classList.add('price__button__amount');
const spanPlus = document.createElement('span').classList.add('price__button__plus');
spanName.textContent = coffee.name;
spanAmount.textContent = coffee.prices.medium;
ul.appendChild(price);
price.appendChild(a);
a.appendChild(spanWrapper);
spanWrapper.appendChild(spanName);
spanWrapper.appendChild(spanAmount);
a.appendChild(spanPlus);
}
});
};
init();
Here is the HTML structure I am trying to generate (the section is commented out, the remaining elements are defined):
<section class="prices highlight spaced">
<h2 class="visually-hidden">Price list</h2>
<ul class="prices__list">
<!--<li class="price">
<a class="price__button">
<span class="price__button__wrapper">
<span class="price__button__name">Oat Latte</span>
<span class="price__button__amount">€ 2</span>
</span>
<span class="price__button__plus">+</span>
</a>
</li> -->
</ul>
</section>