a set of very handy functions

Created by: xing, Last modification: 23 Dec 2005 (10:20 UTC)

The utility functions

The library comes with many predefined objects and utility functions. The obvious goal of these functions is to save you a lot of repeated typing and idioms.

Using the $() function

The $() function is a handy shortcut to the all-too-frequent document.getElementById() function of the DOM. Like the DOM function, this one returns the element that has the id passed as an argument.

Unlike the DOM function, though, this one goes further. You can pass more than one id and $() will return an Array object with all the requested elements. The example below should illustrate this.

        <title> Test Page </title>
        <script src="prototype-1.3.1.js"></script>

            function test1() {
                var d = $('myDiv');

            function test2() {
                var divs = $('myDiv','myOtherDiv');
                for(i=0; i<divs.length; i++) {

        <div id="myDiv">
            <p>This is a paragraph</p>
        <div id="myOtherDiv">
            <p>This is another paragraph</p>

        <input type="button" value=Test1 onclick="test1();"><br>
        <input type="button" value=Test2 onclick="test2();"><br>

Another nice thing about this function is that you can pass either the id string or the element object itself, which makes this function very useful when creating other functions that can also take either form of argument.

Using the $F() function

The $F() function is a another welcome shortcut. It returns the value of any field input control, like text boxes or drop-down lists. The function can take as argument either the element id or the element object itself.

    function test3() {
        alert( $F('userName') );

<input type="text" id="userName" value="Joe Doe"><br>
<input type="button" value=Test3 onclick="test3();"><br>

Using the Try.these() function

The Try.these() function makes it easy when you want to, ahem, try different function calls until one of them works. It takes a number of functions as arguments and calls them one by one, in sequence, until one of them works, returning the result of that successful function call.

In the example below, the function xmlNode.text works in some browsers, and xmlNode.textContent works in the other browsers. Using the Try.these() function we can return the one that works.

    function getXmlNodeValue(xmlNode){
        return Try.these(
            function() {return xmlNode.text;},
            function() {return xmlNode.textContent;}