1

I've always had to use a selector to get elements in the DOM so I could retrieve the data that I need. eg:

var test1 = document.getElementById('testElement').value; // or
var test2 = document.querySelector('#testElement').value; // or
var test3 = $('#testElement').val(); // etc...

Recently, I noticed that I no longer need to do that. Instead, simply using the element's id seems to be sufficient. It seems to be used as a reference to the element. The code below works for me in Chrome, Firefox and even IE9.

var test4 = testElement.value;

I've been trying to find some more information on this but wherever I look, everyone says that selectors need to be used.
So either my colleagues and I completely missed this somehow, or not many people know about this. Or, I suppose, I'm horrible at searching for information.

Basically, I'm looking for more information on this.

So please point me in the right direction so I can investigate further and make sure this functionality is here to stay and can be used consistently.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
17xande
  • 2,430
  • 1
  • 24
  • 33
  • @canon Though I absolutely hate duplicates, I've created another one. Apologies, I will research further next time. Thanks for the link though. It explained the situation well. – 17xande Sep 06 '12 at 20:27

2 Answers2

1

This is a browser feature, which is not according to the specification. This means that for your code to work on most browsers, it should be using some selector. Also, testElement may not work if it already is a global variable.

Some Guy
  • 15,854
  • 10
  • 58
  • 67
0

Depending on the browser the element id may be in the global scope. That is a nice feature and all but I would not depend on this for your applications. If you want to be thorough I suggest using getElementById() or a selector with jQuery.

Gabe
  • 49,577
  • 28
  • 142
  • 181