Search code examples
javascriptarraysfunctionbuttonappendchild

Printing list from an array through a button click/function?


So I added a button that creates an unordered list from an array (var list_content = ["Apple", "Banana", "Orange", "Mango", "Papaya"];), with each array item being shown as a list item li element. I also appended the list to a div target.

var question4 = document.querySelector('#btn4');
question4.addEventListener('click', switch4);

var listContent = ['Apple', 'Banana', 'Orange', 'Mango', 'Papaya'];

function switch4() {
    var newElement = document.createElement('Li');
    div4.appendChild(newElement);
    for (var i = 0; i < listContent.length; i++) {
        newElement.textContent += listContent[i];
    }
}

However when I click the button on my webpage, 'AppleBananaOrangeMangoPapaya' is printed after every button click.

When I change the for loop to be:

 newElement.textContent = listContent[i];

Then all that prints is 'Papaya'.

I need the button to print 'Apple', 'Banana', 'Orange', 'Mango', and 'Papaya' seperately after each button click (so 'Apple' on the first click, 'Banana' on the second click and so forth) but I am stuck on how to do it.


Solution

  • This is happening as you are looping through full listContent array on each button click. You can resolve it by adding a index variable with default value 0 and only adding the listContent element at that index and using post-increment ++ it will keep adding the next element on each click like:

    var div4 = document.querySelector('#div4');
    var question4 = document.querySelector('#btn4');
    var index = 0;
    question4.addEventListener('click', switch4);
    
    var listContent = ['Apple', 'Banana', 'Orange', 'Mango', 'Papaya'];
    
    function switch4() {
      var newElement = document.createElement('Li');
      newElement.textContent = listContent[index++];
      div4.appendChild(newElement);
    }
    #div4 {margin-top:10px;}
    li {margin: 0 10px;padding: 5px 0;}
    <button id="btn4">Click Me</button>
    <div id="div4"></div>