Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Select function Cars-rental

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading