Assigning a one-of-a-kind identifier to a cell within a table that was dynamically created using JavaScript and

When using JavaScript to create table cells and rows and populate them with information from a JSON file, I encounter an issue where the unique ids assigned to the table cells in my code are undefined. This causes problems when trying to reference these ids later on as they appear to be "blank".

I'm puzzled by why this error is occurring as the table is being created and everything seems to display correctly. Below you will find my code along with additional relevant details, please note that I am not using jQuery for this implementation.

HTML:

<div id="info">
    <table id="country">
    </table>
</div>

JavaScript:

document.getElementById("country").innerHTML = "";
for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
    document.getElementById("country").innerHTML += "<tr><td id='" + jsonData.api.countries[i].code + "'>" + "<img src=" + jsonData.api.countries[i].flag + ">" + "<p>" + jsonData.api.countries[i].country + "</p>" + "</td>" +
        "<td id='" + jsonData.api.countries[i + 1].code + "'>" + "<img src=" + jsonData.api.countries[i + 1].flag + ">" + "<p>" + jsonData.api.countries[i + 1].country + "</p>" + "</td>"
        +"</tr>";
}

An error message appears in the console log:

Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction

Below is a screenshot showing how the HTML appears in the page elements:

https://i.sstatic.net/q4Xq5.png

Here is a snippet of the JSON file used:

https://i.sstatic.net/8v9Ez.png

Answer №1

Here's a quick example using vanilla JavaScript along with some custom JSON data:

  
     let jsonData = {
    "countries": [{
            "country": "Brazil",
            "code": "BR",
            "flag": "https://media.api-football.com/flags/br.svg"
        },
        {
            "country": "Canada",
            "code": "CA",
            "flag": "https://media.api-football.com/flags/ca.svg"
        },
        {
            "country": "Italy",
            "code": "IT",
            "flag": "https://media.api-football.com/flags/it.svg"
        }
    ]
};
let htmlContent = ``;

jsonData.countries.forEach((element, index) => {
    htmlContent += `<tr><td id="${element.code}" onclick="showCountryInfo(this)"><img src="${element.flag}"></img><p>${element.country}</p></td><tr>`;
});
document.getElementById('countryData').innerHTML = htmlContent;
const showCountryInfo = (target) => {
    let countryName = target.querySelectorAll('p')[0].innerText;

    alert('This country is ' + countryName)
}
<div id="information">
  <table id="countryData">
  
  </table>
</div>

I hope this example gives you some insight into working with JavaScript and JSON data!

Answer №2

If you encounter the error "Cannot read property 'x' of undefined," it likely means that you are attempting to access a property of an object that is null. I recommend checking the line where you try to access jsonData.api.countries[i+1]. It's possible that when your for loop reaches its last index, you are trying to access an object that does not exist (i+1). To avoid this issue, consider adjusting your loop to continue until jsonData.api.countries.length-1.

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

Enable automatic profile login for the Firebase application

Imagine a web application created using Vue and Firebase. The main query revolves around automatically logging into the app after page reload, particularly accessing the database post authorization. Following user authentication, crucial data such as email ...

Leveraging Circe for JSON string decoding

My Json string contains information about cars and trucks with requesters and providers. val configInfo = { "car": { "requesters": { "request1": "key1", "request2": "key2" }, "provider": { "req ...

The error message "item is not defined in nodejs" indicates that the variable

I am facing an issue while trying to retrieve data from a JSON file using Node.js and Express. I have defined the methods with exports, but I keep getting errors in my browser. I am unsure why it is not functioning correctly, as I have specified the metho ...

Update the promise status to reflect any changes

While attempting to modify the button text based on the promise status, I created a custom directive for this purpose. Below is the code snippet for my custom directive: .directive('myDir',function(){ return { scope: { ...

Blank .json Document in Scrapy

I've created a small spider script in Python to extract the names of colleges from a U.S. News website. #!/usr/bin/python # -*- coding: utf-8 -*- import scrapy class CollegesSpider(scrapy.Spider): name = "colleges" start_urls = [ &a ...

Variable in v-for loop is not properly declared

Currently, I am attempting to iterate through an array of objects retrieved from the backend and display these objects on the frontend. The Vue framework is throwing an error stating that "event" is not defined on the instance but referenced during render. ...

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...

Using Node.js with the Instagram API resulted in the error message: "Failed to decode a text frame in UTF-8 format."

For my project, I am utilizing the Instagram API with the http node.js module. The API call is quite simple: getJSON : function(options, on_result, on_error) { var req = http.request(options, function(res) { var output = ''; ...

Omit specific object properties within a foreach loop in jQuery AJAX

Check Out This Fiddle Example I am currently working with a PHP file that returns JSON data for main content along with an additional property for pagination. I am looking for a way to exclude the pagination property when iterating over the data in a fore ...

sending Immutable.Map objects as parameters in React components

It appears that the popularity of the immutable library for React is on the rise. However, I'm encountering difficulties when trying to utilize Immutable.Map objects as props. It seems that Immutable.Map doesn't mesh well with the spread operator ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...

Modifying Element Values with JavaScript in Selenium using C#

As a newcomer to automation, I am facing a challenge with automating a web page that has a text field. I initially attempted using driver.FindElement(By.XPath("Xpath of elemnt").SendKeys("Value"); but unfortunately, this method did not work. I then resor ...

Hide the HTML DIV without altering the position of the current div

My goal is to conceal elements 1, 3 and 2 & 4 without changing their position. div{ width: 10%; float: left; } <div style="background-color: blue"><p>1</p></div> <div style="background-color: yellow"><p>2</ ...

Strategies for optimizing progressive enhancement

Designing a website that is accessible to everyone is truly an art form, and Progressive Enhancement is something I hold dear... I am curious to hear about the best techniques you have used to ensure websites work for all users, regardless of their browse ...

When using three.js orbitControl, inputting text into textboxes in a Ruby on Rails application is

My three.js application seems to be causing issues with my text field in my Ruby on Rails application. I am unable to write anything in the text field or even click on it. Does anyone know why this is happening? Here is a snippet of my three.js application ...

JavaScript: Retrieving the coordinates of the visible area of an element

Is there a way to calculate the visible area of an element on the screen, taking into account any hidden parts due to CSS properties like overflow: scroll and position: absolute? The goal is to create a function called getVisiblePart(el) that will return ...

Generate a new style element, establish various classes, and append a class to the element

Is there a more efficient solution available? $("<style>") .attr("type", "text/css") .prependTo("head") .append(".bor {border:2px dotted red} .gto {padding:10px; font-size:medium}"); $("input:text").addClass("bor gto").val("Enter your t ...

What is the most efficient method for managing axios errors in Laravel and Vue.js?

Currently, I am developing spa web applications using Laravel as the backend and Vue.js as the frontend framework. For authentication with API, I am utilizing Laravel Passport, and for managing my application state, I am using Vuex. Initially, I created A ...

Vue.js Enhances CoolLightBox with Multiple Galleries

I am trying to set up a page with multiple galleries using CoolLightBox. It worked fine for me when I had just one gallery, but now that I want to create multiple galleries - each with its own image on the page - it is only displaying one image in the ligh ...

Traversing a nested array using jQuery

I'm attempting to utilize jQuery's each function in order to iterate through the provided array. My aim is to identify the key ("Name") and display its corresponding array values on the webpage. Array ( [E-mail] => Array ( ...