简体   繁体   中英

Adding a DOM element to a constructor function in Javascript

if I have a constructor function and want to plug in a DOM element how do I do this? I figure I need to convert it to a string but I'm not sure & I can't quite figure out how to convert it. Thank you.

function MyFunk(domElementVar,domElementString) {

this.domeElementVar = document.getElementById(this.domeElementString);


};

Your current function is a constructor that accepts two arguments: an element and a string. This means you would call it as new MyFunk(document.getElementById(...), "...") .

What you want instead is a constructor that only accepts a string, and finds the element itself. Note that:

  • For arguments, do not use this. . They are variables available inside the function.
  • For properties on the object being constructed, do use this. .

So:

function MyFunk(domElementString) {
  this.domeElementVar = document.getElementById(domeElementString);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM