Create Your Own Custom JavaScript Dollar Function To Select An Element

By  on  

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.

Recent Features

  • By
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

  • By
    Create WordPress Page Templates with Custom Queries

    One of my main goals with the redesign was to make it easier for visitors to find the information that was most popular on my site. Not to my surprise, posts about MooTools, jQuery, and CSS were at the top of the list. What...

  • By
    iPhone-Style Passwords Using MooTools PassShark

    Every once in a while I come across a plugin that blows me out of the water and the most recent culprit is PassShark: a MooTools plugin that duplicates the iPhone's method of showing/hiding the last character in a password field. This gem of...

Discussion

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

    function $(id) {
         return document.getElementById(id);
    }
    
  2. Hi, lets make it smaller ^^

    function $(i) { return document.getElementById(i); }
  3. 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';

  5. Brandon
    function $(e)
    {
     if(e.substring(0,1) == '#')
     {
      return document.getElementById(e.substring(1));
     }
     else
     {
      return document.getElementByClass(e.substring(1));
     }
    }
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!