// Number of stars you have
const nbStars = 4;
// An array where we keep the toggle state of each star
const toggles = [];
// Deal with the stars. One by one
for (let i = 0; i < nbStars; i += 1) {
// Setup the initial state of the toggle
toggles.push(false);
const star = document.getElementById(`star${i + 1}`);
star.addEventListener('click', () => {
if (toggles[i] === true) {
star.innerHTML = 'assets/svg/checked-star.svg';
} else {
star.innerHTML = 'assets/svg/unchecked-star.svg';
}
// Change the state of the toggle for that particular star
toggles[i] = !toggles[i];
});
}
.star {
height: 5em;
width 5em;
background-color: #444444;
margin: 1em;
color: white;
}
<div id="star1" class="star"></div>
<div id="star2" class="star"></div>
<div id="star3" class="star"></div>
<div id="star4" class="star"></div>
Альтернатива с использованием @brk хорошая идея о querySelectorAll
const toggles = Array.from(document.querySelectorAll('[id^="star"]')).map((x, xi) => {
x.addEventListener('click', () => {
if (toggles[xi] === true) {
x.innerHTML = 'assets/svg/checked-star.svg';
} else {
x.innerHTML = 'assets/svg/unchecked-star.svg';
}
// Change the state of the toggle for that particular star
toggles[xi] = !toggles[xi];
});
// Setup the initial state of the toggle
return false;
});
.star {
height: 5em;
width 5em;
background-color: #444444;
margin: 1em;
color: white;
}
<div id="star1" class="star"></div>
<div id="star2" class="star"></div>
<div id="star3" class="star"></div>
<div id="star4" class="star"></div>