No need for document.getElementById?

How is not using document.getElementById('first_name') working here ?
I never knew this was possible. I never thought this could be possible in the first place.

<div>
    <textarea id="first_name">test</textarea>
</div>

<script>
console.log(first_name);
</script>

Is this for any reason not recommended ?
Its one line less code - let first_name = document.getElementById('first_name') - I ALWAYS do this.

I even didn’t know that this is possible and I am not sure if it would work in any browser.

But I would never ever use it. It is a super way to produce logical errors in your code.

  1. Let’s assume you declare anywhere in your code a variable which has the same name as an id of your html element….

  2. When you read the code from another person (or even your own code a few month/years later) you will completely struggle about where this variable comes from.

1 Like

@Paul_Wilkins wrote a post on this a few years ago that you might find interesting.

TLDR: don’t do it :). Always get the element in the proper manner.

4 Likes

Additionally, it has even more bad things than Paul pointed out; it’s type unspecific.

getElementById has two return types: null or Element.

The magic global has at least 3 types; an Exception (if it doesnt exist), an Element, or an ElementCollection.

As we have often seen here, people abuse ID by reusing them.

If you reuse an ID, and getElementById it, you get the first instance of that ID. It’s an Element. (Usually an HTMLElement).

If you reuse an ID, and use the magic global variable… you get a ElementCollection containing all the instances of that ID. ElementCollection (HTMLCollection, etc) does not implement the same methods that Element does. It doesnt behave the same way. Suddenly your if(global_variable) isnt sufficient - you need to test whether it’s a single element or not, too…

1 Like

For me, the bottom line is that if I am developing something that only I will work with then there is usually no need for getElementById. If the code will be seen by others then I might need to to use it.

Part of the problem is the design of the JavaScript language and the way it works with HTML. The problem of not knowing where the variable was defined is one such deficiency. The article referred to previously says was considered to have been a mistake.

It would be relatively easy for an HTML editor to show all the ids in a HTML file. Are there no HTML editors that do that?

Visual Studio Code doesn’t seem to catch it.

One way that instantly comes to mind is to use find and a regex. The following highlights just the id names.

(?<=id=['"])[^'"]+

Just to add, I am very much in the camp of using querySelector or getElementById and assigning that id to a well written variable. Even if the code is just written for myself, I want it to be easy to read and breakdown. Come back a month later to a script with just console.log(first_name) and it’s going to have you scratching your head trying to figure out where that first_name originated from.

That would be true - if the script is embedded in the HTML file.

If it’s a random include and you’re looking at the script file alone… shrug (is it a variable from another include? a global defines? some HTML page somewhere?)

This…this right here is the reason I would ensure I used the getElementById pattern…the few saved keystrokes aren’t worth the time spent trying to figure stuff out when you have to invariably revisit the code.

Which is a security problem just waiting to happen…

I mean… the browser’s going to need access to the script regardless, so I dont know how much of a ‘security risk’ you’re looking at there, but the general traction toward separation of code and display, it’s just plain more likely to be an external file that an IDE cant intuitively backtrace; a script file can be called from many HTML sources, each with different or dynamic values - the element may not exist in the HTML, but as long as it’s created by something (remote fetch, anyone?) before the script function executes, Javascript’s happy.

Inline scripts increase the chances of script jockeys injecting malicious code into your site because they are just easier/more convenient to deal with all in one place. Ran into this recently with a security code scan of an old code base my company maintains, and we ended up spending massive amounts of times getting the inline scripts mitigated…

I didn’t know that this was even possible in my 20+ years of web development.
I having an debate with my colleague about not using it that way but we weren’t in sync.

That capability has been in there for a long time. I can remember using it in IE before it became Edge, so it’s been around a while. I’ve just learned not to use it for the reasons listed above…

You’ve been in web development for 20 years and never used a framework or external function library? Hat’s off to you then, sir.

EDIT: I’ve really gotta have coffee before replying to things. You meant the magic globals. I’ll be honest and say its fairly new to me in the Javascript sphere; certainly familiar with them in PHP. But yeah… its not very intuitive, and its frankly a bad habit to teach, so im not surprised most wouldnt know or use them

Used jQuery till 2021 - using VaniallaJS + AlpineJS + HTMX in current Django based projects.
Plan to use React/Vue using Inertia in Laravel and hopefully in Django as well this year and in the future.

I saw this and my curiosity got to me so I went and did some searching.

I was right that this was introduced in IE (and carried to the other browsers for compatibility sake) as I found threads from 2011 that talks about it. The one thread talks about it being part of the WHATWG HTML spec at one point but it looks like it was removed about five years ago, and I don’t see it there now, though that spec is far worse to read than the W3C version. It gives me a headache trying to decipher it…

HTML Standard (whatwg.org) It’s still there now… (keep in mind that all global variables are properties of the window object.)

EDIT: Specifically:

For Visual Studio (not Visual Studio Code) Microsoft seems to parse C# code in the editor. I think that JetBrains parses PHP code in their PHP IDE.