im trying to achieve something pretty simple. i have a list of items. if i click on one it should give it a class of selected. however if i click on another item in the list. it should remove the selected class from the previous element. this is my javascript code.
const timeRangeWrapper = document.querySelector('.time-range');
const timeOptions = timeRangeWrapper.querySelectorAll('.times .time-option');
timeOptions.forEach((item, i) => {
const domIndex = item.getAttribute('data-item');
item.addEventListener('click', () => {
if (i == domIndex) {
item.classList.add('selected');
} else if (i !== domIndex && item.classList.contains('selected')){
item.classList.remove('selected');
}
});
});
this is my markup
<div class="time-range">
<span class="helper">Please select an exact booking time</span>
<ul class="times">
<li class="time-option" data-item="0">7.00PM</li>
<li class="time-option" data-item="1">7.15PM</li>
<li class="time-option" data-item="2">7.30PM</li>
<li class="time-option" data-item="3">7.45PM</li>
<li class="time-option" data-item="4">8.00PM</li>
</ul>
<div class="btn-wrapper form text-center mt-15">
<button data-accept="true" data-time-exact="false" class="btn booking btn-custom-primary text-small bold text-uppercase">Confirm</button>
</div>
i !== domIndexwhen clicking it.