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
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

Incredible Demos

  • By
    Web Notifications API

    Every UI framework has the same set of widgets which have become almost essential to modern sites: modals, tooltips, button varieties, and notifications.  One problem I find is each site having their own widget colors, styles, and more -- users don't get a consistent experience.  Apparently the...

  • By
    Use Elements as Background Images with -moz-element

    We all know that each browser vendor takes the liberty of implementing their own CSS and JavaScript features, and I'm thankful for that. Mozilla and WebKit have come out with some interesting proprietary CSS properties, and since we all know that cementing standards...

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!