Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a button(generate teams) that randomly splits in 2 an array of inputed data and adds the 2 new arrays to HTML. Everytime i press the button it adds the arrays to the html, so i end up with all the generated arrays beeing displayed . What i'm looking for is to have displayed only the the latest generated arrays, so whenver i press generate have the old generated be replaced by the new ones.

<pre>const getTeams = () => {
  const teamSize = Math.ceil(playersArr.length / 2);

  const teamOne = playersArr.slice(0, teamSize);
  const teamTwo = playersArr.slice(teamSize);

  teams.push(teamOne, teamTwo);

 let tCont = document.getElementById('teams-cont')
 let teamW = document.getElementById('teamOne')
 let teamB = document.getElementById('teamTwo')
  //  TEAM 1

    let ul = document.createElement('ul')
    ul.classList.add('team-container')
    for (let i of teamOne) { 
      let li = document.createElement('li')
      li.classList.add('team-sheet-player')
      li.innerHTML = i
      ul.appendChild(li)
      teamW.appendChild(ul);
      
    }   
    tCont.appendChild(teamW)
  teamSheet.appendChild(tCont);


  //  TEAM 2
    let ulB = document.createElement('ul')
    ulB.classList.add('team-container')
    for (let i of teamTwo) { 
      let li = document.createElement('li')
      li.classList.add('team-sheet-player')
      li.innerHTML = i
      ulB.appendChild(li)
      teamB.appendChild(ulB);
     
    }
    tCont.appendChild(teamB)
  teamSheet.appendChild(tCont);
}

genBtn.addEventListener('click', (e) => {
  getTeams()
})


What I have tried:

I do not want to prevent the button's function, i don't know where to start.
Posted
Updated 29-Sep-22 10:29am
Comments
Richard MacCutchan 29-Sep-22 12:37pm    
Find the existing list in the HTML and replace it.

1 solution

Richard is correct.
Create a "root" node to hold the nodes you are appending.
Then, each time, remove everything from the root node.
Or, remove the root node itself and append it back in, and then append each child to that root.

Check this out: HTML DOM Element remove Method[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900