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?