I'm working on a school task, but I recently got stuck with a textContent issue. I import a JSON file and use the data as a foreach. There are no errors in the.js file, but i receive a typeError: cannot set property 'textContent' of undefined, even though i defined the properties with elements from the JSON file?
When I remove the two lines with textContent, I receive a similar error with the appendChild property: cannot read property 'appendChild' of null.
If i log coffee.name in my forEach, I do get the correct first name. I'm guessing i only get one name since the forEach can't loop further because of the errors further along.
My js code:
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 I'm trying to create (the section in comment, the rest is 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>
You are trying to chain methods together like this:
const test = document.createElement('span').classList.add('price__button__name'); console.log(test.classList);
But, you have to create the element first and then you can work with its classList
or other properties:
const test = document.createElement('span'); test.classList.add('price__button__name'); console.log(test.classList);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.