javascript getter Id of object collection in Class

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>

1 thought on “javascript getter Id of object collection in Class”

  1. There are a couple of issues with the code:

    • You have a self variable in #init that is a copy of this. 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):

    class MyClass {
      #index;
      
      constructor(selector) {
        this.els = document.querySelectorAll('button');
        this.#init();
      }
      
      #init() {
        const self = this;
        Array.from(this.els).forEach((el, index) => {
          const fc = function(){self.#onclick(el)};
          self.#bind(el, 'click', fc, self, index);
        });
      }
      
      #bind(el, event, func, self, index) {
        el.addEventListener(event, func.bind(self, index));
      }
      
      #onclick(...args) {
        const b = arguments[0];
        console.log(b.getAttribute('id'));
      }
    
    }
    
    new MyClass();
    <button id="button1">Button 1</button>
    <button id="button2">Button 2</button>
    Reply

Leave a Comment