streetparade
streetparade

Reputation: 32878

How to create own jQuery-like function in JavaScript?

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?

Upvotes: 5

Views: 1028

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163228

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.

Upvotes: 9

Tgr
Tgr

Reputation: 28160

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.

Upvotes: -1

Related Questions