Consider this JavaScript code here (in Browser JavaScript):
var x = document.getElementById("demoID");
x.style.color = "blue";
- 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>
- 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.