Jump to content
FrankieGTH

Declaring an HTML ID not necessary in Javascript - The questions

Recommended Posts

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:

  1. Since when is that?
  2. How about browser support?
  3. Does W3Schools mention that anywhere and if not, why not?

Share this post


Link to post
Share on other sites

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!

Share this post


Link to post
Share on other sites

Although it works -- as a part of browser backward-compatibility -- I doubt that anyone recommends that approach anymore.

Share this post


Link to post
Share on other sites

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>

 

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

×