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;
};