5

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?

2
  • 13
    So, Bob comes along to look at some code that has landed in his lap and discovers that it is using a $ function. "%$@£%!", he sighs, "Is this jQuery? No. Maybe prototype.js is in there somewhere? Oh, it's a custom routine. Why can't people give their variables useful names?" Commented Apr 25, 2010 at 20:35
  • Name the function something like getElem("id") if you want to shorten document.getElementById("id"). I wrote some like that before and added a optional context parameter for iframes etc. getElem("id", context). This was before I discovered jQuery. Using $ would just be confusing to anyone else reading your code. Commented Apr 25, 2010 at 22:59

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.