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.
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 ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.