Utility Methods Atom feed
Prototype provides a number of “convenience” methods. Most are aliases of other Prototype methods, with the exception of the $
method, which wraps DOM nodes with additional functionality.
These utility methods all address scripting needs that are so common that their names were made as concise as can be. Hence the $
-based convention.
The most commonly used utility method is without doubt $()
, which is, for instance, used pervasively within Prototype’s code to let you pass either element IDs or actual DOM element references just about anywhere an element argument is possible. It actually goes way beyond a simple wrapper around document.getElementById
; check it out to see just how useful it is.
These methods are one of the cornerstones of efficient Prototype-based JavaScript coding. Take the time to learn them well.
Methods
$
$(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. Takes in an arbitrary number of arguments. All elements returned by the function are extended with Prototype DOM extensions.
$$
$$(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.
$A
$A(iterable) -> actualArray
Accepts an array-like collection (anything with numeric indices) and returns its equivalent as an actual Array
object. This method is a convenience alias of Array.from
, but is the preferred way of casting to an Array
.
$F
$F(element) -> value
Returns the value of a form control. This is a convenience alias of Form.Element.getValue
. Refer to it for full details.
$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 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
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
deprecated
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.