3.1. Utility Functions

Prototype adds a handful of utility functions into JavaScript that although simple, are very useful.

3.1.1. The $ function

The global function $ plays a similar role to document.getElementById. However, as well as being much more terse, $ has the following advantages.

  • It can be passed either ids or the elements themselves.

  • It can be passed multiple arguments to yield an array of Elements.

  • The objects it returns "mix in" the Element Prototype object.

var el = $(id); // finding the element by id
el = $(el);     // finding an element by the element
var images = $("mouseoverimage","mouseoutimage"); // finding multiple elements by ids

Locating an element, given the element itself, may seem pretty pointless until you consider the situation when you don't know if you have an element id or the element itself. By using the $ function, you know you definitely have the element. This technique is used to allow other prototype functions to work on either the element or the id.

3.1.2. The $F function

The global function $F allows quick access to form values. It takes the id of the form field and returns the value. In the extract below, the values for the name and gender from the form:

<FORM>
             <INPUT name="name" id="name" TYPE="text" value="textval">
             <SELECT name="gender" id="gender">
                       <OPTION value="M">male</option>
                       <OPTION value="F">female</option>
             </SELECT>
</FORM>

may be accessed via $F("name") and $F("name"). Again, the $F function can take either the id or the element ...

Get Prototype and Scriptaculous: Taking the Pain out of JavaScript 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.