PrototypeUtilityFunctions

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.


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

        <script>
            function test1() {
                var d = $('myDiv');
                alert(d.innerHTML);
            }

            function test2() {
                var divs = $('myDiv','myOtherDiv');
                for(i=0; i<divs.length; i++) {
                    alert(divs[i].innerHTML);
                }
            }
        </script>
    </head>

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

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


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.


<script>
    function test3() {
        alert( $F('userName') );
    }
</script>

<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.


<script>
    function getXmlNodeValue(xmlNode){
        return Try.these(
            function() {return xmlNode.text;},
            function() {return xmlNode.textContent;}
        );
    }
</script>