Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using

document.body.appendChild(createList(rolesData[~~(Math.random()*rolesData.length)].roles));
). This works well, but now I want to add functionality to allow changing the list by clicking a button to display roles for different names, each with varying numbers of roles.

The challenge is that each person has a different number of roles, making it difficult to update the list dynamically. I attempted to assign ids to the list items and change them using getElementById, but this approach falls short when new items need to be added beyond the initially created ones. I am seeking help and suggestions on how to achieve this feature effectively.

const rolesData = [{
   "name": "John Smith",
   "title": "project manager",
   "roles": ["Planning and Defining Scope", "Activity Planning and Sequencing", "Resource Planning"],
  },
  {
   "name": "Mary Taylor",
   "title": "test analyst",
   "roles": ["design and develop tests for software and systems to detect faults", "analyse the defects and bugs to identify what is causing them", "track the success of the solutions", "keep software and systems documentation up to date"],
  }
  ];

const createList = data => {
  const list = document.createElement("ul");

 data.forEach(e => {
   const listItem = document.createElement("li");
   listItem.innerHTML = e;
   list.appendChild(listItem);
 });

 return list;
};

document.body.appendChild(createList(rolesData[~~(Math.random()*rolesData.length)].roles));

(This is the approach I had been trying to take, which obviously won't work).

const createList = data => {
const list = document.getElementById("featuredList");
count = 1;
data.forEach(e => {
 const listItem = document.getElementByID("listItem" + count);
 listItem.innerHTML = e;
 list.appendChild(listItem);
 count++;
});
return list;
};

Answer №1

Instead of replacing the contents, eliminate the existing list and generate a new one

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

Cannot transfer variables from asynchronous Node.js files to other Node.js files

Is there a way to export variable output to another Node.js file, even though the asynchronous nature of fs read function is causing issues? I seem to be stuck as I am only getting 'undefined' as the output. Can someone help me identify where I ...

Is there a way to launch QTP from JavaScript without relying on ActiveXObject?

Is there a way to call QTP from JavaScript without relying on ActiveXObject? I would appreciate any guidance on how to accomplish this task. Thanks in advance, Ramya. ...

What could be causing the "function undefined" error in my HTML document?

Recently, I developed a small chat application that initially functioned well with all code contained in one HTML document. However, after separating the CSS, HTML, and JS into individual files, an issue arose when invoking the register_popup function from ...

Ways to reduce the size of images within a bootstrap carousel

I'm currently working on creating a carousel that will serve as a background image cover for my website, similar to the revolutionary slider in WordPress but without using a plugin. I am developing it specifically for my static website. The challenge ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Is it possible to perform an inline ternary operation or if-else statement within a JSON array?

My JSON array structure is as follows: { "appName": "MyApp", "restricted_mode": true, "some_array": [ { "module_1": "abc", "type": "internal", "comp ...

What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server. The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I ...

Following the submission of a message, the textarea automatically inserts a line-break

Can someone please help me troubleshoot an issue with my chat app? Every time I try to send a message, the textarea adds a line break instead of just focusing on the textarea so I can send a new message smoothly. I have recorded a video demonstrating the ...

Update the user information by using its unique identifier at a specific location

I am currently working on editing user data with a specific MongoDB instance. When I click on the user's details, a modal popup appears with an update button below it. My goal is to have the user data updated when this button is clicked for the partic ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...

Disabling a button based on the state of a switch button using React and Material UI

For the task at hand, we need to ensure that the button is only activated when the switch button's state changes. This state is received as a prop and needs to be validated correctly within the handleChangeState function. const CustomSwitch = ({name, ...

Utilizing JSON data for efficient React component rendering

As a newcomer to React, I am currently in the process of constructing a dashboard that showcases data from three different sensors. The information regarding these sensors is stored in a single JSON file where each sensor has its own ID and name. This JSON ...

Error encountered when attempting to insert data into database due to incompatible data types

I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

An Angular directive utilizing dual aliases

Is there a simple method to give a directive two distinct names? For example: app.directive(['directiveNameOne', 'directiveNameTwo'], function() {...}); I have created a directive that handles both radio buttons and checkboxes in th ...

Is it impossible to access the length property of an undefined variable?

After developing a function that calculates the length of a string entered into an HTML textbox, I encountered an error when trying to display the result in another textbox. The function is designed to get the value from the 5th textbox on my HTML page and ...

Exploring the potential of PHP's reset function along with associative arrays

I am attempting to iterate through an associative array using the functions current(), next(), and reset(). While the first two functions are working as expected, I am encountering an issue when trying to loop through the array again after using the reset( ...

Replace the term "controlled" with "unleashed" when utilizing the file type input

In my app, I have defined multiple states like this: const [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''}) And to get an image from my device, I am using the following input: &l ...

What could be causing PySpark to encounter a JSONDecodeError while trying to convert a string from a Kafka topic into a dictionary?

Utilizing Spark Structured Streaming to ingest data from a Kafka topic in JSON format for transformation within Spark has hit a roadblock. The initial phase involves reading records as strings and converting them into dictionaries using Python's json ...

Achieving success was like uncovering a hidden treasure chest after a successful

Is there a way to address this JSON data issue? success{"data": [{"id":"1","name":"something1"},{"id":"2","name":"something2"},{"id":"3","name":"something3"}] } The success variable contains the JSON data. This is how the server script returns the data: ...