Tuesday, November 30, 2010

JavaScript dollar sign function ($)

If you have been working with JavaScript in recent years you may be aware of the wide used of the dollar sign function. Generally, the dollar sign function is use as a shortcut to document.getElementById and document.getElementByName; however, it can be use for anything. So here is the version of the dollar sign function that I will be using in other JavaScript examples within this blog.



function $() {
    var elements = [];
    var e = null;
    for (var i = 0; i < arguments.length; i++) {
        var element = null;
        var arg = arguments[i];
        if (typeof arg == 'string') {
            element = document.getElementById(arg);
            if (element === null) {
                element = document.getElementsByTagName(arg);
                if (element.length == 1) {
                    element = element[0];
                }
            }
            if (element.length === 0) {
                element = document.getElementsByName(arg);
                /* note: IE does not return this as an array so only the first element
                in the collection (only if more than one exists) will be accessible.*/
                if (element.length === 1) {
                    element = element[0];
                }
                e = element;
            }
        } else {
            element = arg;
        }
        if (arguments.length == 1) {
            return element;
        }
        if (element !== null) {
            elements.push(element);
        }
    }
    return elements;
}



Usage
Accessing an element by id:
document.getElementById('id').innerHTML = 'Hello World';
With the dollar function would be:
$('id').innerHTML = 'Hello World';


Accessing an element by name:
document.getElementByName('name').innerHTML = 'Hello Tokyo';
With the dollar function would be:
$('name').innerHTML = 'Hello Tokyo';


Accessing more than one element at a time:
for (var i = 0; i < 2; i++) {
           $('name1', 'name2')[i].innerHTML = "test";
}




Compress this code here

No comments:

Post a Comment