Search code examples
javascripthtmlarraysdomappendchild

Create a new element for every item in an array, appending (issue)


My issue is that every time I press the button it keeps adding. I want it to replace it self.

It's likely that there are better ways to approach this. I want to be able to present all the data in an array, with one new element per item in the array.

I only use vanilla JS

const reBtn = document.getElementById("reBtn");

reBtn.addEventListener("click", function () {
  myfunc();
});

let sortedList = ["1", "2", "3", "4"];
let addParagraph = document.createElement("ul");

function myfunc() {
  sortedList.forEach(function (i) {
    let li = document.createElement("li");
    li.textContent = i;
    addParagraph.appendChild(li);
    resultLeft.appendChild(addParagraph);
  });
}
<button id="reBtn">Result</button>

<div id="resultLeft"></div>


Solution

  • const reBtn = document.getElementById("reBtn");
    
    reBtn.addEventListener("click", myfunc)
    
    const sortedList = ["1", "2", "3", "4"];
    const ulElement = document.createElement("ul");
    
    function myfunc() {
      ulElement.textContent = ""
      sortedList.forEach(function (i) {
        const li = document.createElement("li");
        li.textContent = i + " [" + new Date().getSeconds() + "]";
        ulElement.appendChild(li);
      });
      resultLeft.appendChild(ulElement);
    }
    <button id="reBtn">Result</button>
    
    <div id="resultLeft"></div>