The T-Files


Wed, 05 Oct 2005

var navBar = $('navigationBar');

I was quite surprised to see this code pattern in a JavaScript file recently. How could I have missed this useful and elegant $(id) syntax to look up a DOM element? Was this something new, invented recently by the browser makers? Maybe Mozilla-only? I definitely did not recall it being mentioned in the Rhino book, or anywhere else for that matter.

Turns out it is just an ordinary function, declared in the popular prototype library (which the file I was looking at was built upon). For some reason, the JavaScript syntax allows for the dollar sign to be used in identifier names, and even for their first character, so that they can write very clever function definitions:

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1) 
      return element;

    elements.push(element);
  }

  return elements;
}

There is also a function $F(name), which looks up form element values.