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
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Incredible Demos

  • By
    9 Incredible CodePen Demos

    CodePen is a treasure trove of incredible demos harnessing the power of client side languages.   The client side is always limited by what browsers provide us but the creativity and cleverness of developers always pushes the boundaries of what we think the front end can do.  Thanks to CSS...

  • By
    Send Email Notifications for Broken Images Using jQuery AJAX

    It's usually best to repair broken image paths as soon as possible because they can damage a website's credibility. And even worse is having a user tell you about it. Using jQuery and PHP, you can have your page automatically notify you of broken...

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!