Unable to retrieve text content from dynamically created element in JavaScript?

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">&euro; 2</span>
          </span>
          <span class="price__button__plus">+</span>
        </a>
      </li> -->
  </ul>
</section>

Answer №1

When attempting to chain methods together, you may be doing it like this:

const example = document.createElement('div').classList.add('example__class');
console.log(example.classList);

However, it is important to first create the element and then manipulate its properties like classList:

const example = document.createElement('div');
example.classList.add('example__class');
console.log(example.classList);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered during upgrade from version 10 to version 13 in a Next.js migration: Module not found

I've been working on upgrading our old site from version 10 to version 13, and we have a custom backend built with express. However, I keep encountering a "Module not found" error when running the project concurrently, specifically when running the cl ...

Passing Data from Child Components to Parent Components in Vue.js

Looking for assistance with a component I have: <BasicFilter></BasicFilter> It contains a select element: <select @change="$emit('onSortName', $event)"> <option value="asc"> A..Z</option><opti ...

delete the final directory from a file directory

let currentLocation = window.location.pathname; let directory = currentLocation.substring(0, currentLocation.lastIndexOf('/')); The current location is: /examples/html/home/ The directory is: /examples/html/home I am trying to remove the las ...

Dropdown for state selection within WooCommerce for specific countries

I am encountering a challenge in configuring a form with default WooCommerce country and states selection dropdowns. Essentially, my goal is to present the Country selection first, followed by the State selection based on the chosen country. For instance, ...

What is the optimal method for showcasing functions in NodeJS?

In my project, I have a directory specifically for all my DAO files. These DAO files are responsible for interacting with the MySQL server. The structure of my DAO directory includes: | -- dao | -- user.dao.ts | -- employee.dao.ts Additionally, I hav ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

Demonstrating the transformation of child elements into parent elements through angular 6 ngFor

I have a JSON array dataset where each object may contain nested arrays. In order to display the inner nested array elements as part of the parent array using Angular's NgFor, I need to format the input like this: [{ 'id': 1, 'tit ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Setting an HTML element ID on a material-ui component: A step-by-step guide

I have a website that was created using Gatsby.js and incorporates the Material-UI framework. The specific issue at hand is as follows: I am looking to implement Google Tag Manager "Element Visibility" triggers. The goal is for GTM to trigger a Google Ana ...

Puzzled by the unexpected error I encountered while using Node.js (require.js)

My script was running smoothly until I encountered a sudden error: undefined:3 <!DOCTYPE html> ^ SyntaxError: Unexpected token < at Object.parse (native) at Request._callback (C:\Users\Tom\Pictures&bso ...

Transmitting special characters like umlauts through JSON using HTTPRequest

I am encountering a challenge in sending a JSON string via POST to a web service hosted on Azure within my Xamarin Forms application. While the JSON communication with the server is functional, I am facing difficulties specifically with umlaut characters. ...

Local host's attempt to retrieve data from an external site via an Axios GET request was rejected

I'm currently attempting to execute a GET request on an external website in order to scrape some information. Unfortunately, my axios GET request is returning a connection error. I suspect that this issue may be related to the fact that I am sending t ...

What is the process for spinning a span in the center of an image?

My canvas displays an image: https://i.sstatic.net/p3MV4.png There is a white square with a refresh icon on the right side of the image, slightly hidden by a black circle. I implemented it like this: var rotatorSpan = document.createElement("span"); rot ...

Feetable information in JSON format

I have a footable that I want to populate with JSON data. I am familiar with how to fill the array, but I am using some PHP to retrieve my data using the echo json_encode method. When I console.log the response, it gives me : [{"idsecteur":"1","nomsecte ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

What steps are involved in implementing Local fonts in theme UI for Next JS?

I am currently developing an application using next JS with [theme-UI][1]. However, I need to implement local or custom fonts in my project and I'm unsure of how to do this. Below is the current theming setup: const theme = { fonts: { ...

Mongoose fails to carry out internal query using Promise mechanism

Just diving into the asynchronous and await world, I decided to play around with Mongoose + MongoDB + Node.JS. Here is a snippet of my code: exports.updateBrandPreferences = async (req,res) => { var userID = req.body.playerID; var newBrands = r ...

Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" colum ...

What is the correct way to import the THREE.js library into your project?

I recently added the three library to my project via npm. Within the node_modules directory, there is a folder named three. However, when I tried to import it using: import * as THREE from 'three'; I encountered the following error: ReferenceEr ...