Jump to content

Declaring an HTML ID not necessary in Javascript - The questions

Recommended Posts


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?
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>


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.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...