Friday, July 13, 2007

Prototype Javascript Framework - Utility Methods

Here it is a quick review of the most important utility methods of the Prototype Framework. (This was taken of the Prototype reference document that you can find in http://beta.bigmedium.com/projects/prototype-pdf/index.shtml)

$

$(id | element) -> HTMLElement
$((id | element)...) -> [HTMLElement...]

If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element.

The function also extends every returned element with Element.extend so you can use Prototype's DOM extensions on it.

$$

$$(cssRule...) -> [HTMLElement...]

Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them.

The $$ function searches, by default, the whole document.

Current set of supported selectors:

  • Type selector: tag names, as in div.

  • Descendant selector: the space(s) between other selectors, as in #a li.

  • Attribute selectors: the full CSS 2.1 set of [attr], [attr=value], [attr~=value] and [attr|=value]. It also supports [attr!=value]. If the value you're matching against includes a space, be sure to enclose the value in quotation marks ([title="Hello World!"]).

  • Class selector: CSS class names, as in .highlighted or .example.wrong.

  • ID selector: as in #item1.


$A

$A(iterable) -> actualArray

Accepts an array-like collection (anything with numeric indices) and returns its equivalent as an actual Array object.

$A doesn't perform DOM extensions, since the array could contain anything (not just DOM elements).

$F

$F(element) -> value

Returns the value of a form control. This is a convenience alias of form.Element.getValue.

$H

$H([obj]) -> Hash

Creates a Hash (which is synonymous to “map” or “associative array” for our purposes).

A convenience wrapper around the Hash constructor, with a safeguard that lets you pass an existing Hash object and get it $F | 5 back untouched (instead of uselessly cloning it).

$R

$R(start, end[, exclusive = false]) -> ObjectRange

Creates a new ObjectRange object. This method is a convenience wrapper around the
[ObjectRange](/api/objectRange constructor, but $R is the preferred alias.

$w

$w(String) -> Array

Splits a string into an Array, treating all whitespace as delimiters. Equivalent to Ruby's %w{foo bar} or Perl's qw(foo bar).

Try.these

Try.these(Function...) -> firstOKResult

Accepts an arbitrary number of functions and returns the result of the first one that doesn't throw an error.

document.getElementsByClassName

document.getElementsByClassName(className[, element]) -> [HTMLElement...]

Retrieves (and extends) all the elements that have a CSS class name of className. The optional element parameter specifies a parent element to search under.