const carSelector = document.querySelectorAll(".cars-select");
const car = document.querySelectorAll(".car");
carSelector.forEach((selected, index) => {
selected.addEventListener("click", () => {
car.forEach((car) => {
car.classList.remove("show");
});
car[index].classList.add("show");
});
});
This is showing all the time first element, doesn’t matter on which select i click.
I think that "index" is == 0; but idk how to change it.
>Solution :
The problem with your code is that the index variable doesn’t work as expected. To fix this, we can use the function keyword.
Please mark as correct answer if it helped.
const carSelector = document.querySelectorAll(".cars-select");
const car = document.querySelectorAll(".car");
carSelector.forEach(function(selected, index) {
selected.addEventListener("click", function() {
car.forEach((car) => {
car.classList.remove("show");
});
car[index].classList.add("show");
});
});
.car {
display: none;
}
.car.show {
display: block;
}
<div class="cars-select">Car 1</div>
<div class="cars-select">Car 2</div>
<div class="cars-select">Car 3</div>
<div class="car">Car 1 details...</div>
<div class="car">Car 2 details...</div>
<div class="car">Car 3 details...</div>