Back

Technologies:

javascriptjavascript
avatar
Tolerim
22 days ago

Reworded sentence: How can I transform a function to behave like an instance of a class?

Initially, I created a script that only worked on a single group of elements, with a listener on the parent id:

<div id="parent-element">
  <div class="sub_element">
  <div class="sub_element">
  <div class="sub_element">
</div>
However, I now need to initialize this function on multiple groups of elements. Simply calling the function with different parent ids will not work as the script is not an instance, and variables in the script just get overridden when interacting with different element groups. Although I could convert the code into an object, save data by parentId, and make individual instances of the script, re-calling the function would still result in the variable overwrite issue. Is there any better solution to this problem or is it incurable?

Answers(2)
avatar
Vogi
22 days ago
Verified Answer
You can use the document.querySelectorAll() method to select all elements that match a specified CSS selector(s), and returns a NodeList object. You can then loop through the NodeList object and apply the function to each element. Here's an example:
function myFunction() {
  var x = document.querySelectorAll(".sub_element");
  var i;
  for (i = 0; i < x.length; i++) {
    // Do something with each element here
  }
}
In this example, the function selects all elements with the class name "sub_element" and loops through them one by one. You can replace ".sub_element" with any valid CSS selector(s) that match your desired elements. I hope this helps! Let me know if you have any other questions.

Sources

C Arrays - GeeksforGeeksDifferent ways to Initialize all members of an array to the same value ...Initialize multiple arrays in function C programmingObject and Collection Initializers - C# Programming GuideTuple types - C# reference | Microsoft Learn
avatar
Tolerim
22 days ago
One way to solve this problem is to convert the function into a class and create instances of it for each group of elements. This way, each instance will have its own set of variables that won't interfere with each other. Here's an example of how you can do it:
class SomeClass {
  constructor(parentElementId, options) {
    this.parentElementId = parentElementId;
    this.someField1 = null;
    this.someField2 = null;
    // more variables
    // very long code related to the group of elements with parent element with id="parent-element"
  }

  someMethod() {
    // access class variables using this.variableName
  }
}
Then you can create instances of this class for each group of elements like so:
const instance1 = new SomeClass("parent-element", optionsObj);
const instance2 = new SomeClass("parent-element-2", optionsObj2);
Each instance will have its own set of variables that won't interfere with each other. You can call instance methods on each instance separately without overriding the variables.
;