I have a problem with my JavaScript code. I have an object. Inside that object are two objects. They have a string called 'name' and an array called 'description'. I loop through these items and display their 'name'. When an item is clicked, I pass the item that was clicked to a new function.
In the new function, I loop through it's 'description' array and display the list item. The problem is that when I click on one, I want to delete the description of the previous one I clicked on and replace with the one I just clicked. Here is the code:
/* items object which contains two objects that
contain a name and a description array*/
var items = {
item1: {
name: 'item1',
description: [
'bye from item1',
'hello from item1'
]
},
item2: {
name: 'item2',
description: [
'bye from item2',
'hello from item2'
]
}
}
/*Looping through objects in the items object and displaying their
name in a list*/
for(let i in items){
var listItem = document.createElement('li');
listItem.textContent = items[i].name;
ol.appendChild(listItem);
/*calling function when item is clicked, passing in the
clicked item*/
listItem.onclick = function(){
newFunction(items[i]);
}
}
/*function for displaying description array of the clicked item, invoked
when item is clicked*/
function newFunction(passedListItem){
for(var i = 0; i < passedListItem.description.length; i++){
var listItem = document.createElement('li');
listItem.textContent = passedListItem.description[i];
ul.appendChild(listItem);
}
}