0

I need to expose the istance of a class to be called from the dom element.

i've created a class that i'll instance as new myCustomClass(). This class is related to a DOM element.

What i need to do in my class to access to his methods and property form the dom?

I need something like this (this is something that swiper.js do)

var foo = document.querySelector('.element-where-class-is-instanced').myCustomClass;
foo.init()

thanks to all

7
  • 1
    "I need to expose [… on] the dom element." - really? Why? This is usually considered a bad idea. Commented Mar 31, 2022 at 15:49
  • @Bergi swiper.js do it, so i dont think this is so bad Commented Mar 31, 2022 at 15:51
  • 1
    It is. And you haven't explained what you think you need this for. Commented Mar 31, 2022 at 15:54
  • In certain situation I need to read some property o run some method of the Class that is related to that element. For example, re init the carousel with some different parameter. And I need to do this after the page is compiled Commented Mar 31, 2022 at 16:04
  • 1
    What do you mean by "the page is compiled"? And why can't you simply store the result of calling new myCustomClass() in a normal variable? Commented Mar 31, 2022 at 16:11

1 Answer 1

2

Just assign the class instance to the element property earlier:

document.querySelector('.element-where-class-is-instanced').myCustomClass = new myCustomClass();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.