Solution 1 :

As discussed below the question, the problem was that list items were being added and the existing items remained. The solution was to clear the list beforehand:

function rank() {
   var el = document.getElementById('rank')
   el.innerHTML = ""
   characters.forEach(function (character) {   
      el.innerHTML += '<li>' + character.name + '</li>
})}

Problem :

I have a list of names with points assigned to each one, each time i click on a button related to that name it adds a point then it ranks them in the html file when pressing the rank button, everything works fine but when i make changes and click rank again it adds another list instead of updating the existing one:

let characters = [
   {name: document.getElementById("name 1").textContent, points: 0},
   {name: document.getElementById("name 2").textContent, points: 0},
   {name: document.getElementById("name 3").textContent, points: 0}
];

function choice (button) {
   const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
   buttonCharacterObject.points += 1;
   const ranking = characters.sort((a, b) => (a.points < b.points ? 1 : -1));
   console.log(ranking);
}

function rank() {
   characters.forEach(function (character) {   
      document.getElementById('rank').innerHTML += '<li>' + character.name + '</li>
})}

<button id="name 1" onclick="choice(this)">Martin</button>
<button id="name 2" onclick="choice(this)">Sam</button>
<button id="name 3" onclick="choice(this)">John</button>
<button onclick="rank()">Rank Characters</button>
<ol id="rank">
    
</ol>

Comments

Comment posted by Jan Stránský

“it adds another list” doesn’t it just push another

Comment posted by Marten Prod

@Jan Stránský yes sorry for not explaining it well, it goes : 1- name 1, 2- name 2, 3- name 3, 4- name 1, 5- name 2, 6- name 3

Comment posted by Jan Stránský

Then it just follows what you ask the program to do. Inside

Comment posted by Marten Prod

and how do i do that ?

Comment posted by Jan Stránský

.innerHTML=""

Comment posted by Marten Prod

yes, i’m very new to this that’s why i couldn’t guess it, is it okay if i write the code like this ? although yours is much neater:

Comment posted by Jan Stránský

Depends on definition of okay 🙂 The code works, so it may be okay. From

Comment posted by Marten Prod

okay i will do as u suggested, thank you so much for the help

Comment posted by Jan Stránský

Just to make it clear, I just wrote here

By