Here's something I use in my own library. DOM is the class and $ is a function which is a shortcut implementation of the getElementById function:
function DOM()
{
this.$ = function(elementIDs)
{
var el;
// If an array of element names is passed.
if (arguments.length > 1)
{
var elements = [];
var length = arguments.length;
for (var i = 0; i < length; i++)
{
// Call this function recursively for each passed parameter.
elements.push(this.$(arguments[i]));
}
return elements;
}
// If a single element name is passed.
if (typeof(elementIDs) == "string")
{
el = document.getElementById(elementIDs);
}
return el;
}
}
The initial block creates the global object FB. They use this object, FB, as a namespace and define all their objects, properties, and functions within it. That way, it will work with other JavaScript code as long as that other code doesn't use the global object FB.
When you've seen the $() function, it was probably some library such as jQuery or Prototype. The $ function is not an alias for document.getElementById, but is a wrapper that extends the functionality of the function.
To create your own wrapper, you could write a function "alias":
var alias = document.getElemenyById;
or
function alias(id) { return document.getElementById(id); }
But really, I would use one of the libraries available such as jQuery or Prototype.
Here's something I use in my own library.
DOM
is the class and$
is a function which is a shortcut implementation of thegetElementById
function:Usage:
You can alias it to the top level window element.
Possibly the easiest/shortest way:
facebook's connect-js does the following in src/core/prelude.js:
Then, to use it, they do:
The initial block creates the global object FB. They use this object, FB, as a namespace and define all their objects, properties, and functions within it. That way, it will work with other JavaScript code as long as that other code doesn't use the global object FB.
When you've seen the $() function, it was probably some library such as jQuery or Prototype. The $ function is not an alias for document.getElementById, but is a wrapper that extends the functionality of the function.
To create your own wrapper, you could write a function "alias":
or
But really, I would use one of the libraries available such as jQuery or Prototype.
The new features introduced in ES6 let us improve on Chris Lloyd's answer, simplifying:
to: