javascript - Using a document method from within object prototype? -


i'm pretty new javascript , trying set prototype called "number" key called "button" grabs html element whatever id pass it. there element id of "one" present in html.

i'm wondering why doesn't work?

function number(num, idofnum) {  this.val = num;  this.button = document.getelementbyid(idofnum); };  var 1 = new number(1, "one");  console.log(one.button); // null? 

if one.button null, that's because document.getelementbyid("one"); did not find dom object when ran constructor number() object , returned null.

that either because there no object in page id or becase running code before page has finished loading , object not yet exist when run code.

you have show more of overall page context (where code executing in relation parsing of page dom) know situation happening here.

a common fix situation you're running code move <script> tag code resides right before </body> tag. ensure dom elements exist when code runs. more complete explanation of issue see answer: pure javascript equivalent jquery's $.ready() how call function when page/dom ready it.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -