tags:

views:

82

answers:

2

How can i create a function which looks like the jquery callback $

Say i want to call a element with id= "mydiv".

i want to be able to call it like

var div = $("mydiv").value;

i think the function should look like

function $(element)
{
  return  document.getElementById(element);
}

Is that the right way to do it, or do you prefer another way to solve it?

+7  A: 

You can do it one of three ways:

local scope:

function $(element)
{
  return  document.getElementById(element);
}

or

var $ = function(element)
{
  return  document.getElementById(element);
}

or if you need it to be defined in global scope:

window.$ = function(element)
{
  return  document.getElementById(element);
}

If you have included jQuery, defining $ in the global scope will override it. Use jQuery.noConflict to avoid this.

Jacob Relkin
A: 

jQuery actually returns a custom object so you can call $('#id').someJqueryFunction(). If you simply want a shortcut for document.getElementById,

var $ = document.getElementById;

should suffice.

Tgr
Will fail in many browsers. Remember that when you extract a method from an object and then call it from the now-unbound reference, `this` will not be set. So calling `$` will not pass the right `document` object to the `getElementById` function.
bobince
Well, `this` will be set, but to `window` rather than `document`. Still breaks though ;)
David Dorward