How do you access the id of an element that’s in a collection in a class using the getter and setter methods on click event for the buttons in my example code below
class MyClass {
#index;
constructor(selector) {
this.els = document.querySelectorAll('button');
this.#init(this);
}
get Id() {
return this.els[this.#index].getAttribute('id');
}
#init(self) {
Array.from(this.els).forEach((el, index) => {
self.#index = index;
self.#bind(el, 'click', self.#onclick, self, index);
});
}
#bind(el, event, func, self, index) {
el.addEventListener(event, func.bind(self, index));
}
#onclick(...args) {
console.log(this.Id);
}
}
new MyClass();
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
There are a couple of issues with the code:
You have a
self
variable in#init
that is a copy ofthis
. Every time you set a value for#self.index
you are overwriting the previous value held at#this.index
. In other words,#this.index
only has the last value you set at#init
.Related to that, the
#onclick
function has no information about which button has been pressed. It gets information on the last button that was processed by#init
.If you only need to pass the button that has been clicked to
#onclick
, you do not need to keep track of indexes with getters or setters. The key is to pass a variable to#onclick
(fc
in the code):