I'm trying to get into object oriented javascript programming. I have written a class for collapsible elements as a test. These elements all have a certain class and no matter how many elements there are on the page, they should all be collapsible.
It works so far, but I don't think it's very elegant yet. For example, I wonder if the function "checkforCollapsibles" doesn't actually belong in the class. But, can a class create instances of itself?
But, that's probably not the only thing. I would be very happy if you have any suggestions on how to make this even better, cleaner and more elegant.
I know you don't need a class for collapsing elements.
"use strict";
class bb_Collapsible {
  constructor(link, content) {
    this.link = link;
    this.content = content;
    this.content.classList.toggle("bb-collapsed");
    this.link.addEventListener("click", this);
  }
  handleEvent(event) {
    if (event.type === "click") {
      this.switchStatus();
    }
  }
  switchStatus() {
    this.content.classList.toggle("bb-collapsed");
  }
}
function checkForCollapsibles() {
  const collapsibleLinks = document.querySelectorAll(".bb-collapsible");
  const collapsibleContents = document.querySelectorAll(".bb-collapsible-content");
  if (collapsibleLinks.length > 0) {
    collapsibleLinks.forEach((element, index) => {
      new bb_Collapsible(collapsibleLinks[index], collapsibleContents[index]);
    });
  } else {
    console.log("No collapsible Elements");
  }
}
document.addEventListener("DOMContentLoaded", checkForCollapsibles);
EXTENSION
I used this article for event handling. However, I don't quite understand it yet. In the example, only pass this as the callback. I assume javascript interprets this as the eventHandle function of the respective instance. But, what if I have different elements that should trigger different functions? In my example, I could only ask which event was triggered and not which element. Or, should I then write switches and get it from the respective event object? But, that no longer sounds clean and tidy to me.
https://dev.to/rikschennink/the-fantastically-magical-handleevent-function-1bp4