Cover by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Revisiting the getElementById Function

In Chapter 13, I mentioned the common usage of the $ character as a function name to provide easier access to the getElementById function. In fact, major frameworks such as jQuery use this new $ function, and substantially extend its functionality.

I would like to provide you with an enhanced version of this function too, so that you can handle DOM elements and CSS styles quickly and efficiently. However, to avoid conflicting with frameworks that use the $ character. I’ll simply use the uppercase O as the function name, since it’s the first letter of the word Object, which is what will be returned when the function is called (the object represented by the ID passed to the function).

The O Function

Here’s what the bare-bones O function looks like:

function O(obj)
{
    return document.getElementById(obj)
}

This alone saves 22 characters of typing each time it is called, but I’ve chosen to extend the function a little by allowing either an ID or an object to be passed to this function, as shown in the complete version of the function in Example 20-1.

Example 20-1. The O function

function O(obj)
{
    if (typeof obj == 'object') return obj
    else return document.getElementById(obj)
}

If an object is passed to the function, it just returns that object back again. Otherwise, it assumes that an ID has been passed and returns the object to which the ID refers.

But why on earth would I want to add this first statement, which simply returns the object passed to it?

The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required