0

I have an OnClick event and each img element has a unique numerical identifier defined in "data-index".

The goal is to change css class of both elements when the image or span element are clicked.

Right now I can only toggle the class of either the image or the span element This is like a character select screen.

function selector() {

  var getSlots = Array.from(document.querySelectorAll('.slotimage', '.charname'));
  for (var i = 0; i < getSlots.length; i++) {
    getSlots[i].dataset.index = i;
    getSlots[i].onclick = function(e) {
      var index = this.dataset.index;

      if (this.classList.contains('unselected')) {
        this.classList.toggle("unselected");
        this.classList.add("selected");
      } else {
        this.classList.toggle("selected");
        this.classList.add("unselected");
      }
    };
  }
}

I have tried using getSlots[i].classlist but I keep getting an error. If I don't use "this" then nothing works

I've got ~30 items so I need to toggle the styles of the one I clicked

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    `document.querySelectorAll()` only takes one argument. Why are you calling it with two arguments? If you want to select both `.slotimage` and `.charname`, use `'.slotimage, .charname'` in a single argument. – Barmar Aug 11 '23 at 00:11
  • Change `var i` to `let i` and then you can use `getsSlots[i]` inside the `onclick` function. See https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Barmar Aug 11 '23 at 00:13
  • But I'm not sure how this relates to the problem. `getSlots[i]` will always be the same as `this`, they're both the element that you click on. I don't see how you're trying to access two different elements when you click on just one. – Barmar Aug 11 '23 at 00:16
  • Is the image inside the span? Put the click listener on the span. Then you can use `this.querySelector("img")` to get the image inside it. – Barmar Aug 11 '23 at 00:17

0 Answers0