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