1

Consider this JavaScript code here (in Browser JavaScript):

  var x = document.getElementById("demoID");
  x.style.color = "blue";
  1. Is it safe to replace it with this working code:
 demoID.style.color = "blue";

HTML5:

<!DOCTYPE html>
<html>
<body>

<p id="demoID">Click the button to change the color of this paragraph.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  // var x = document.getElementById("demoID");
  // x.style.color = "blue";
  demoID.style.color = "blue";
}
</script>

</body>
</html>
  1. What about performance (speed) comparing to document.getElementById?

Edit:
I did a micro-benchmark document.getElementById is 3.7x faster:

HTML:

    <input type="checkbox" id="checkboxSigned" onchange="numberBase10changed()">Signed

    <div id="div2"></div>

JavaScript:

    let signed=false;
    let t0 = performance.now();
    for (let i=0; i<1000000; i++){
        // signed = document.getElementById("checkboxSigned").checked; // 88ms to 116ms
        signed = checkboxSigned.checked; // 369ms to 398ms
        g++;
    }
    div2.innerText = g+"interval = " + Math.trunc( performance.now()-t0 ) + "ms";

Result for signed = document.getElementById("checkboxSigned").checked;

88ms to 116ms

Result for signed = checkboxSigned.checked;

369ms to 398ms

Thanks in advance for your help.

wasmup
  • 14,541
  • 6
  • 42
  • 58
  • How could you call that "a working code"? Have you tried it? – Addis Dec 28 '19 at 13:13
  • Yes, it works on my Chrome, Firefox, and Opera. – wasmup Dec 28 '19 at 13:14
  • 2
    I can't try this at the moment, but it would be a surprise for me if this worked, I would guess that "demo" is undefined and it fails at that line. – whatamidoingwithmylife Dec 28 '19 at 13:14
  • 2
    @it'sBritneybitch The code doesn't fail at that line. New variables named by id attribute values are created to the global scope automatically, if the ids are unique within the document. – Teemu Dec 28 '19 at 13:18

1 Answers1

0

Safe? .. Yes. Readable? .. No.

First, this works because all id's are added to the window object. So JS will continue to traverse up the parent's scope till it hits the window.

Though I think this affects readability. It's unclear where demo is referenced or initialised. As you'll be looking for a variable declaration that you'll never find.

From the HTML spec:

window[name]

Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

Community
  • 1
  • 1
C.OG
  • 6,236
  • 3
  • 20
  • 38