Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element accessible with ID

Tags:

javascript

I saw a strange behavior. I created a Input.

<input id='inputid' value='value'/>​

and tried to access it directly from id. Instead of throwing an exception console was showing above input element.

console.log(inputid);

After that I tried to compare it with getElementById

console.log( inputid == document.getElementById('inputid'));

console was showing true.

You can see this behavior on jsfiddle.

Is it a strange behavior or am I missing something?

I tested it in Chrome 23.0.1271.10 dev-m and firefox 15.0.1.

like image 212
Anoop Avatar asked Sep 30 '12 18:09

Anoop


2 Answers

Back in the days of 4.0 browsers, Microsoft decided that it would be convenient to create, for every element with an id, a global variable with the same name as the id containing a reference to that element.

Support for this has appeared in some other browsers (in some rendering modes). This support is not universal so the feature should be avoided.

like image 140
Quentin Avatar answered Oct 06 '22 08:10

Quentin


To just expand a little on this situation based on a curiosity:

<html><head>
<script type="text/javascript">
  var overWrite = "world";
  window.onload = function(){ alert(overWrite); };
</script></head><body>
<input id="overWrite" value="hello" />
</body></html>

Will alert "world". However, with //var overWrite = "world"; (as in with that line commented out), it will alert the [html element]. Note that this is after the page loads so it is persistent and not some sort of temporary assignment.

Strongly agree that it should not be used due to inconsistency and readability issues.

EDIT

Still was curious about this issue and did some more testing. I was curious if access was faster with document.getElementById or by variable reference. Made this test:

html

<div id="contentZone"></div>

js

var startTime = Date.now();
for( var i = 0; i < 1000; i++){
    for( var n = 0; n < 2000; n++){
        var ni = document.getElementById("contentZone");
    }
}
var endTime = Date.now();
console.log( endTime - startTime );

var aTime = Date.now();
for( var i = 0; i < 1000; i++){
    for( var n = 0; n < 2000; n++){
        var ni = contentZone;
    }
}
var bTime = Date.now();
console.log( bTime - aTime );

console

431
814

Tested on this machine only, but it would seem that using document.getElementById is still faster making this variable access even less desirable.

like image 32
Travis J Avatar answered Oct 06 '22 09:10

Travis J