FrankieGTH Posted May 10, 2018 Share Posted May 10, 2018 Hi, I had a function in which I forgot to declare the ID of an element that played an important role in it. But the function still worked, without any console error reports; I saw the omission only today. At first I almost didn't believe it, but the demo linked from https://www.w3schools.com/jsref/prop_html_id.asp confirmed it. If you change that function to function displayResult() { myHeader.innerHTML = "Have a nice day!"; } it works just as well. That raises a few questions: Since when is that? How about browser support? Does W3Schools mention that anywhere and if not, why not? Link to comment Share on other sites More sharing options...
dsonesuk Posted May 10, 2018 Share Posted May 10, 2018 IF the id value is myHeader then myHeader.innerHTML = "Have a nice day!"; Will work as that is dot notation which has been about for a whille now! Link to comment Share on other sites More sharing options...
justsomeguy Posted May 10, 2018 Share Posted May 10, 2018 There's an article here if you want more information: https://www.tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/ Link to comment Share on other sites More sharing options...
davej Posted May 10, 2018 Share Posted May 10, 2018 Although it works -- as a part of browser backward-compatibility -- I doubt that anyone recommends that approach anymore. Link to comment Share on other sites More sharing options...
justsomeguy Posted May 10, 2018 Share Posted May 10, 2018 That article has some good reasons why it's not the best idea to count on that. A simple reason would be that you simply can't refer to some elements like that. None of these will be available: <div id="document"> <span id="alert">We have moved:</span> <span id="location">New address</span> </div> Link to comment Share on other sites More sharing options...
FrankieGTH Posted May 14, 2018 Author Share Posted May 14, 2018 Thank you, gentleman. I guess the JS devs forgot to write me about this change. 😉 I'll keep declaring vars and constants, if it were only because the next web dev that has to work with my scribbles may be a junior one. Who may see undeclared items as globals, which would confuse them. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now