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>

68 thoughts on “javascript getter Id of object collection in Class”

  1. Fantastic site you have here but I was wondering if you knew of any community forums that cover the same
    topics talked about here? I’d really like to be a part of community
    where I can get comments from other experienced individuals that share the same interest.
    If you have any recommendations, please let me know. Thanks! http://cleckleyfloors.com/

    Reply

Leave a Comment