I know this tutorial is not about the best code but I couldn't help myself from refactoring your code ;).
<!DOCTYPE html><htmllang="en"><head><title>State Management in Vanilla JS</title></head><body><divid="app"></div><script>constApp={state:{count:0,},template(){return`
<h1>Hello Vanilla JS!</h1>
<div>
Example of state management in Vanilla JS
</div>
<br />
<h1 id="counter">${this.state.count}</h1>
<button id="button">Increase</button>
`;},initialize(){document.getElementById('app').innerHTML=this.template();document.getElementById("button").addEventListener("click",()=>App.increment());},increment(){this.state.count++;this.updateUI();},updateUI(){document.getElementById('counter').textContent=this.state.count;}};App.initialize();</script></body></html>
"app" in "app.innerHTML" has no reference, even though the code works perfectly. Can you please enlighten me? Pardon me me for being a novice. I was expecting something like app = document,getElementById("app")
Both app and template exist because each DOM node that has a defined id attribute gets added to the global window object and therefore is able to be referenced without explicit initialization. This is part of the reason why id attributes should be unique for each DOM node in the tree.
Try it with another DOM node and a different id!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi Vijay Pushkin,
I know this tutorial is not about the best code but I couldn't help myself from refactoring your code ;).
"app" in "app.innerHTML" has no reference, even though the code works perfectly. Can you please enlighten me? Pardon me me for being a novice. I was expecting something like app = document,getElementById("app")
Hey Afisunlu, totally a valid question:
Both
appandtemplateexist because each DOM node that has a definedidattribute gets added to the globalwindowobject and therefore is able to be referenced without explicit initialization. This is part of the reason whyidattributes should be unique for each DOM node in the tree.Try it with another DOM node and a different
id!