0

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);
    }
}
  • You have a closure to *i*, so `newFunction(items[i])` will always pass the last item for all listeners. See [*JavaScript closure inside loops – simple practical example*](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). Also see [*How to create a minimal, complete and verifiable example*](http://stackoverflow.com/help/mcve). – RobG May 13 '17 at 11:51
  • I don't think that's the problem. It's not the passing. It's just when I click on it, I would like to replace the previous one with the latest one. Currently it's just duplicating. – Scratch Cat May 13 '17 at 11:53

1 Answers1

0

Well, if you only have the description in the ul, you can remove all its children like this :

while (ul.firstChild) {
    ul.removeChild(ul.firstChild);
}

Otherwise, you have to store the number of elements to remove like this :

Put toRemove = 0 before your function declaration :

toRemove = 0;
function newFunction(passedListItem){

and then in the function, remove the toRemoventh last child

while((toRemove > 0) && (ul.lastChild)){
    ul.removeChild(ul.lastChild);
    toRemove -= 1;
}

and after that, set toRemove to the number of the new description

toRemove = passedListItem.description.length
Alex
  • 1,368
  • 10
  • 20