2

I've been coding with vanilla JS for quite a few years, but whenever I needed to handle an HTML element with an id attribute I'd reasonably resort to:

var myId = document.getElementById('myId');

When, by mere accident, I actually found out that this works:

function add() {
  let span = document.createElement('span');
  span.innerHTML = '<br />o hi';

  // === THIS: ===
  correctId.appendChild(span);

}
<div id="someId"></div>
<input type="button" value="MOAR" onclick="add()" />
<div id="correctId"><strong>Append here: </strong></div>
<div class="someClass"></div>

I was beyond shocked to learn this.

The million dollar question is... Is that even good practice or standard at all? Can I safely use that in my code or is it a very recent addition, deprecated, browser-specific or even dangerous?

I didn't even know how to look for references on this behavior. I tried looking for "element id as variable", "using ids as var names" and so on. Nothing. Everywhere I go people mention document.getElementById(), document.querySelector('#'), jQuery, but never that one behavior - that elements with an id attribute are already available as variables in JavaScript, or at least that's how I understood it.

I'm using Chrome 81.0.4044.138. Can anyone please shed any lights on this?

gyohza
  • 736
  • 5
  • 18
  • 1
    Your `correctId` is actually `window.correctId`. Also, regarding your question (*"is it appropriate?"*), check this: https://stackoverflow.com/q/25325221/5768908 – Gerardo Furtado May 21 '20 at 23:47
  • Thanks. These are really helpful, and it really is all that I needed! That behavior did feel quite shady to begin with. – gyohza May 22 '20 at 00:33
  • Hello, this feature is available from a long while started with internet explorer 4 or something but not recommended and discourage to use as this will create global variables and starts naming conflicts. One more important thing when you use this feature and for Example: Assume that you used fetch as your id name it will not work it will throw undefined. As the fetch keyword is reserved for fetch API and similarly, if new APIs introduced in future with similar names to your ids then your code will break and you will not have any clue what has happened to your code. – MD M Nauman May 22 '20 at 00:59

1 Answers1

-2

I don't see any problem with this. All you are doing is getting the reference in an indirect way and then adding it using inner Html. I am no expert but do this all the time.

  • I think "I don't see any problem" and "I am no expert but do this all the time" without pointing to docs on it or at least elaborating a bit further on the rationale behind the assertions don't solve or clarify much. However, the post was marked as duplicate, which does shed light on my question. – gyohza May 22 '20 at 00:30