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>
})}
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>
@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
Then it just follows what you ask the program to do. Inside
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:
Depends on definition of okay 🙂 The code works, so it may be okay. From