Create Your Own Custom JavaScript Dollar Function To Select An Element

The "dollar" function has become famous in recent years due to its inception in many popular JavaScript frameworks. MooTools, for example, uses the dollar function to select a single element from the DOM. This functionality is extremely helpful as it allows you to keep your code extremely short and readable, not to mention document.getElementById(''); can get annoying quickly.

The Code

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

You don't need to use a JavaScript framework to compact your code. If you frequently select unique DOM elements, you should create a dollar function for the sake of yourself and your users.


Comments

  1. Jesse Skinner

    To cut the number of getElementById() calls in half, you could just do:

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

  2. Marc

    Hi,

    lets make it smaller ^^

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

  3. Daniel15

    Can you just do:

    var $ = document.getElementById;

    ? I didn’t test this.

  4. Paul

    This function returns null and does not work when I do
    $(‘x’).style.background=’orange’;


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: