Solution 1 :

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.

Problem :

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?

Comments

Comment posted by stackoverflow.com/q/25325221/5768908

Your

Comment posted by gyohza

Thanks. These are really helpful, and it really is all that I needed! That behavior did feel quite shady to begin with.

Comment posted by MD M Nauman

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.

Comment posted by gyohza

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.

By

Leave a Reply

Your email address will not be published. Required fields are marked *