SlideShare a Scribd company logo
PROTOTYPE Utility Methods
INTRODUCTION 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 $(), 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. These methods are one of the cornerstones of efficient Prototype-based JavaScript coding.   
TOPIC INDEX $ $$ $A $F $H $R $w Try.these document.getElementsByClassName
$ $(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. The  $  function is the cornerstone of Prototype.  Not only does it provide a handy alias for  document.getElementById , it also lets you pass indifferently IDs (strings) or DOM node references to your functions: function foo(element) {      element = $(element);      /*  rest of the function... */ } Code written this way is flexible — you can pass it the ID of the element or the element itself without any type sniffing.
Invoking it with only one argument returns the element, while invoking it with multiple arguments returns an array of elements (and this works recursively: if you're twisted, you could pass it an array containing some arrays, and so forth).  As this is dependent on  getElementById , W3C specs apply: nonexistent IDs will yield null and IDs present multiple times in the DOM will yield erratic results. If you're assigning the same ID to multiple elements, you're doing it wrong! The function also  extends every returned element  with  Element.extend  so you can use Prototype's DOM extensions on it.  In the following code, the two lines are equivalent. However, the second one feels significantly more object-oriented: // Note quite OOP-like... Element.hide( 'itemId' );   // A cleaner feel, thanks to guaranted extension $( 'itemId' ).hide(); However, when using iterators, leveraging the $ function makes for more elegant, more concise, and also more efficient code: //common way: [ 'item1' ,  'item2' ,  'item3' ].each(Element.hide); // The better way: $( 'item1' ,  'item2' ,  'item3' ).invoke( 'hide' ); <<Back
$$ $$(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. Sometimes the usual tools from your DOM arsenal –  document.getElementById()  encapsulated by  $() ,  getElementsByTagName()  and even Prototype’s very own  getElementsByClassName()  extensions – just aren’t enough to quickly find our elements or collections of elements. If you know the DOM tree structure, you can simply resort to CSS selectors to get the job done. Performance: when better alternatives should be used instead of $$ Now, this function is powerful, but if misused, it will suffer performance issues. So here are a few guidelines:   If you’re just looking for elements with a specific CSS class name among their class name set, use Prototype’s  document.getElementsByClassName()  extension. Better yet: if this search is constrained within a given container element, use the  Element.getElementsByClassName()  extension.
Those methods should be favored in the case of simple CSS-class-based lookups, because they’re, at any rate, faster than  $$ . On browsers supporting DOM Level 3 XPath, they’re potentially blazing fast.  Now, if you’re going for more complex stuff, indeed use  $$ . But use it well. The  $$ function searches , by default,  the whole document . So if you can, scope your CSS rules as early as you can, e.g. by having them start with ID selectors. That’ll help reduce the search tree as fast as possible, and speed up your operation. Examples $$ ('div') // -> all DIVs in the document.  Same as document.getElementsByTagName('div')!   $$ ( ' #contents ' ) // -> same as $('contents'), only it returns an array anyway.   $$ ('li.faux') // -> all LI elements with class 'faux'   $$ ( ' #contents a[rel] ' ) // -> all links inside the element of ID &quot;contents&quot; with a rel attribute   $$ ('a[href=&quot;#&quot;]') // -> all links with a href attribute of value &quot;#&quot; (eyeew!)   $$ ( ' #navbar li' , ' #sidebar li ' ) // -> all links within the elements of ID &quot;navbar&quot; or &quot;sidebar&quot;
Supported CSS syntax The $$ function does not rely on the browser’s internal CSS parsing capabilities (otherwise, we’d be in cross-browser trouble…), and therefore offers a consistent set of selectors across all supported browsers. The flip side is, it currently doesn’t support as many selectors as browsers that are very CSS-capable.   Here is the 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=&#8221;Hello World!&#8221;])   Class selector: CSS class names, as in .highlighted or .example.wrong. ID selector: as in #item1.   However, it currently does not support child selectors (>), adjacent sibling selectors (+), pseudo-elements (e.g. :after) and pseudo-classes (e.g. :hover). <<Back
$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. The primary use of  $A() is to obtain an actual Array object based on anything that could pass as an array (e.g. the NodeList or HTMLCollection objects returned by numerous DOM methods, or the predefined arguments reference within your functions). The reason you would want an actual Array is simple: Prototype extends Array to equip it with numerous extra methods, and also mixes in the Enumerable module, which brings in another boatload of nifty methods. Therefore, in Prototype, actual Arrays trump any other collection type you might otherwise get. The conversion performed is rather simple: null, undefined and false become an empty array; any object featuring an explicit  toArray  method (as many Prototype objects do) has it invoked; otherwise, we assume the argument &quot;looks like an array&quot; (e.g. features a length property and the [] operator), and iterate over its components in the usual way.
Examples The well-known DOM method  document.getElementsByTagName() doesn't return an Array, but a NodeList object that implements the basic array &quot;interface.&quot; Internet Explorer does not allow us to extend Enumerable onto NodeList.prototype, so instead we cast the returned NodeList to an Array: var  paras =  $A (document.getElementsByTagName( 'p' )); paras.each(Element.hide); $(paras.last()).show(); Notice we had to use each and Element.hide because $A doesn't perform DOM extensions, since the array could contain anything (not just DOM elements). To use the hide instance method we first must make sure all the target elements are extended: $A (document.getElementsByTagName( 'p' )).map(Element.extend).invoke( 'hide' ); Want to display your arguments easily? Array features a join method, but the arguments value that exists in all functions does not inherit from Array. So, the tough way, or the easy way? // The hard way... function  showArgs() {    alert(Array.prototype.join.call(arguments,  ', ' )); }   // The easy way... function  showArgs() {    alert( $A (arguments).join( ', ' )); } <<Back
$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. <<Back
$H $H([obj]) -> EnumerableHash The only way to obtain a hash (which is synonymous to “map” or “associative array” for our purposes). Returns a new object featuring all the methods in the Hash and Enumerable modules. If an original object was passed, clones all its properties in the result before mixing in the modules. The  $H  function is the only proper way to obtain a hash. Indeed, Hash is a module, not a class participating in Prototype’s class mechanism: doing a  new Hash() is not going to help much: it will raise a ”Hash is not a constructor” error. The Hash module is designed to be mixed into objects that also mix in Enumerable, so the  $H  function makes sure it provides you with a result object that mixes in both of those. You can call  $H() without any argument: you’ll obtain an “empty” hash (one that only features the methods in the mixed-in modules). If you pass it an argument, it starts by cloning out the passed object before mixing the modules in. Any property from that object whose name conflicts with a method in the modules will therefore get erased. <<Back
$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. ObjectRange  instances represent a range of consecutive values, be they numerical, textual, or of another type that semantically supports value ranges. See the type’s documentation for further details, and to discover how your own objects can support value ranges. The $R function takes exactly the same arguments as the original constructor: the lower and upper bounds (value of the same, proper type), and whether the upper bound is exclusive or not. By default, the upper bound is inclusive.
Examples $R ( 0 ,  10 ).include( 10 ) // -> true   $A ( $R ( 0 ,  5 )).join( ', ' ) // -> '0, 1, 2, 3, 4, 5'   $A ( $R ( 'aa' ,  'ah' )).join( ', ' ) // -> 'aa, ab, ac, ad, ae, af, ag, ah'   $R ( 0 ,  10 ,  true ).include( 10 ) // -> false   $R ( 0 ,  10 ,  true ).each( function (value) {    // invoked 10 times for value = 0 to 9 }); Note that  ObjectRange  mixes in the Enumerable module: this makes it easy to convert a range to an Array ( Enumerable  provides the  toArray  method, which makes the  $A  conversion straightforward), or to iterate through values.  Note, however, that getting the bounds back will be more efficiently done using the start and end properties than calling the  min() and  max()  methods. <<Back
$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). This is one of those life-savers for people who just hate commas in literal arrays. Examples $w( 'apples bananas kiwis' ) // -> ['apples', 'bananas', 'kiwis']   This can slightly shorten code when writing simple iterations:   $w( 'apples bananas kiwis' ).each( function (fruit){    var  message =  'I like '  + fruit    // do something with the message })   This also becomes sweet when combined with Element functions:   $w('ads navbar funkyLinks').each(Element.hide); <<Back
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. This method provides a simple idiom for trying out blocks of code in sequence. Such a sequence of attempts usually represents a downgrading approach to obtaining a given feature.   In this example from Prototype's Ajax library, we want to get an  XMLHttpRequest  object. Internet Explorer 6 and earlier, however, does not provide it as a vanilla JavaScript object, and will throw an error if we attempt a simple instantiation. Also, over time, its proprietary way evolved, changing COM interface names. Try.these  will try several ways in sequence, from the best (and, theoretically, most widespread) one to the oldest and rarest way, returning the result of the first successful function. If none of the blocks succeeded,  Try.these  will return undefined, which will cause the  getTransport  method in the example below to return false, provided as a fallback result value.
getTransport:  function () {    return  Try.these(      function () {  return   new  XMLHttpRequest() },      function () {  return   new  ActiveXObject( 'Msxml2.XMLHTTP' ) },      function () {  return   new  ActiveXObject( 'Microsoft.XMLHTTP' ) }    ) ||  false ; } <<Back
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. Note that each returned element has been extended.
Example HTML:    <body>      <div id=&quot;one&quot; class=&quot;foo&quot;>Single class name</div>      <div id=&quot;two&quot; class=&quot;foo bar thud&quot;>Multiple class names</div>      <ul id=&quot;list&quot;>        <li id=&quot;item_one&quot; class=&quot;thud&quot;>List item 1</li>        <li>List item 2</li>        <li id=&quot;item_two&quot; class=&quot;thud&quot;>List item 3</li>      </ul>    </body>   JavaScript:    document.getElementsByClassName( 'foo' ); // -> [HTMLElement, HTMLElement] (div#one, div#two)      document.getElementsByClassName( 'thud' ); // -> [HTMLElement, HTMLElement, HTMLElement] (div#two, li#item_one, li#item_two);      document.getElementsByClassName( 'thud' , $( 'list' ));    // -> [HTMLElement, HTMLElement] (li#item_one, li#item_two)   <<Back

More Related Content

PPTX
Java script arrays
Frayosh Wadia
 
KEY
Xtext Eclipse Con
Sven Efftinge
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PPTX
11. session 11 functions and objects
Phúc Đỗ
 
PDF
Handout - Introduction to Programming
Cindy Royal
 
PPTX
Js types
LearningTech
 
PPT
Advanced php
hamfu
 
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Java script arrays
Frayosh Wadia
 
Xtext Eclipse Con
Sven Efftinge
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
11. session 11 functions and objects
Phúc Đỗ
 
Handout - Introduction to Programming
Cindy Royal
 
Js types
LearningTech
 
Advanced php
hamfu
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 

What's hot (20)

PPTX
About Python
Shao-Chuan Wang
 
ODP
Perl Teach-In (part 2)
Dave Cross
 
PPT
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
PPTX
ActionScript3 collection query API proposal
Slavisa Pokimica
 
PDF
Extending the Xbase Typesystem
Sebastian Zarnekow
 
PDF
Few simple-type-tricks in scala
Ruslan Shevchenko
 
PPTX
Python: Basic Inheritance
Damian T. Gordon
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PPT
Javascript built in String Functions
Avanitrambadiya
 
PPT
Complex Data Binding
Doncho Minkov
 
PPTX
Ios development
elnaqah
 
PPTX
Objective c slide I
Diksha Bhargava
 
KEY
Parte II Objective C
Paolo Quadrani
 
PPTX
Object Oriented JavaScript
Julie Iskander
 
PDF
Textual Modeling Framework Xtext
Sebastian Zarnekow
 
PPTX
Linq Introduction
Neeraj Kaushik
 
PPTX
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
PDF
DevNation'15 - Using Lambda Expressions to Query a Datastore
Xavier Coulon
 
PPTX
OO in JavaScript
Gunjan Kumar
 
About Python
Shao-Chuan Wang
 
Perl Teach-In (part 2)
Dave Cross
 
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
ActionScript3 collection query API proposal
Slavisa Pokimica
 
Extending the Xbase Typesystem
Sebastian Zarnekow
 
Few simple-type-tricks in scala
Ruslan Shevchenko
 
Python: Basic Inheritance
Damian T. Gordon
 
JavaScript - An Introduction
Manvendra Singh
 
Javascript built in String Functions
Avanitrambadiya
 
Complex Data Binding
Doncho Minkov
 
Ios development
elnaqah
 
Objective c slide I
Diksha Bhargava
 
Parte II Objective C
Paolo Quadrani
 
Object Oriented JavaScript
Julie Iskander
 
Textual Modeling Framework Xtext
Sebastian Zarnekow
 
Linq Introduction
Neeraj Kaushik
 
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
Xavier Coulon
 
OO in JavaScript
Gunjan Kumar
 
Ad

Viewers also liked (9)

PPT
Php Calling Operators
mussawir20
 
PPT
Php Simple Xml
mussawir20
 
PPT
Php Operators N Controllers
mussawir20
 
PPT
Php String And Regular Expressions
mussawir20
 
PPT
Database Design Process
mussawir20
 
PPT
Chapter 3 Consumer Behaviour
provost33
 
PPTX
Theory Of Consumer Behavior
Kishore Raveendran
 
PPT
Introduction To Macro Economics
Saurabh Goel
 
PDF
Microeconomics: Utility and Demand
Manuel Salas-Velasco, University of Granada, Spain
 
Php Calling Operators
mussawir20
 
Php Simple Xml
mussawir20
 
Php Operators N Controllers
mussawir20
 
Php String And Regular Expressions
mussawir20
 
Database Design Process
mussawir20
 
Chapter 3 Consumer Behaviour
provost33
 
Theory Of Consumer Behavior
Kishore Raveendran
 
Introduction To Macro Economics
Saurabh Goel
 
Microeconomics: Utility and Demand
Manuel Salas-Velasco, University of Granada, Spain
 
Ad

Similar to Prototype Utility Methods(1) (20)

PPT
Generics Collections
phanleson
 
PPT
Prototype Js
Kivanc Kanturk
 
ODP
Practical catalyst
dwm042
 
PPT
ASP.NET 08 - Data Binding And Representation
Randy Connolly
 
PPT
Element
mussawir20
 
PDF
Object Trampoline: Why having not the object you want is what you need.
Workhorse Computing
 
PPTX
Collections
sagsharma
 
PPTX
Introduction to es6
NexThoughts Technologies
 
PPT
JavaScript Workshop
Pamela Fox
 
PPT
Generics collections
Yaswanth Babu Gummadivelli
 
PPTX
Introduction to Client-Side Javascript
Julie Iskander
 
PPTX
Advance oops concepts
Sangharsh agarwal
 
PPT
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
PPTX
Introduction to JQuery
Muhammad Afzal Qureshi
 
PPT
Reversing JavaScript
Roberto Suggi Liverani
 
PPTX
Selenium-Locators
Mithilesh Singh
 
PPT
Enumerable
mussawir20
 
PDF
Ruby On Rails
Balint Erdi
 
PPTX
iOS Session-2
Hussain Behestee
 
PPS
Advance Java
Vidyacenter
 
Generics Collections
phanleson
 
Prototype Js
Kivanc Kanturk
 
Practical catalyst
dwm042
 
ASP.NET 08 - Data Binding And Representation
Randy Connolly
 
Element
mussawir20
 
Object Trampoline: Why having not the object you want is what you need.
Workhorse Computing
 
Collections
sagsharma
 
Introduction to es6
NexThoughts Technologies
 
JavaScript Workshop
Pamela Fox
 
Generics collections
Yaswanth Babu Gummadivelli
 
Introduction to Client-Side Javascript
Julie Iskander
 
Advance oops concepts
Sangharsh agarwal
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
Introduction to JQuery
Muhammad Afzal Qureshi
 
Reversing JavaScript
Roberto Suggi Liverani
 
Selenium-Locators
Mithilesh Singh
 
Enumerable
mussawir20
 
Ruby On Rails
Balint Erdi
 
iOS Session-2
Hussain Behestee
 
Advance Java
Vidyacenter
 

More from mussawir20 (20)

PPT
Php Sq Lite
mussawir20
 
PPT
Php Sessoins N Cookies
mussawir20
 
PPT
Php Rss
mussawir20
 
PPT
Php Reusing Code And Writing Functions
mussawir20
 
PPT
Php Oop
mussawir20
 
PPT
Php My Sql
mussawir20
 
PPT
Php File Operations
mussawir20
 
PPT
Php Error Handling
mussawir20
 
PPT
Php Crash Course
mussawir20
 
PPT
Php Basic Security
mussawir20
 
PPT
Php Using Arrays
mussawir20
 
PPT
Javascript Oop
mussawir20
 
PPT
Html
mussawir20
 
PPT
Javascript
mussawir20
 
PPT
Object Range
mussawir20
 
PPT
Date
mussawir20
 
PPT
Prototype js
mussawir20
 
PPT
Template
mussawir20
 
PPT
Class
mussawir20
 
PPT
Hash
mussawir20
 
Php Sq Lite
mussawir20
 
Php Sessoins N Cookies
mussawir20
 
Php Rss
mussawir20
 
Php Reusing Code And Writing Functions
mussawir20
 
Php Oop
mussawir20
 
Php My Sql
mussawir20
 
Php File Operations
mussawir20
 
Php Error Handling
mussawir20
 
Php Crash Course
mussawir20
 
Php Basic Security
mussawir20
 
Php Using Arrays
mussawir20
 
Javascript Oop
mussawir20
 
Javascript
mussawir20
 
Object Range
mussawir20
 
Prototype js
mussawir20
 
Template
mussawir20
 
Class
mussawir20
 

Recently uploaded (20)

PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 

Prototype Utility Methods(1)

  • 2. INTRODUCTION 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 $(), 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. These methods are one of the cornerstones of efficient Prototype-based JavaScript coding.  
  • 3. TOPIC INDEX $ $$ $A $F $H $R $w Try.these document.getElementsByClassName
  • 4. $ $(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. The $ function is the cornerstone of Prototype. Not only does it provide a handy alias for document.getElementById , it also lets you pass indifferently IDs (strings) or DOM node references to your functions: function foo(element) {      element = $(element);      /*  rest of the function... */ } Code written this way is flexible — you can pass it the ID of the element or the element itself without any type sniffing.
  • 5. Invoking it with only one argument returns the element, while invoking it with multiple arguments returns an array of elements (and this works recursively: if you're twisted, you could pass it an array containing some arrays, and so forth). As this is dependent on getElementById , W3C specs apply: nonexistent IDs will yield null and IDs present multiple times in the DOM will yield erratic results. If you're assigning the same ID to multiple elements, you're doing it wrong! The function also extends every returned element with Element.extend so you can use Prototype's DOM extensions on it. In the following code, the two lines are equivalent. However, the second one feels significantly more object-oriented: // Note quite OOP-like... Element.hide( 'itemId' );   // A cleaner feel, thanks to guaranted extension $( 'itemId' ).hide(); However, when using iterators, leveraging the $ function makes for more elegant, more concise, and also more efficient code: //common way: [ 'item1' ,  'item2' ,  'item3' ].each(Element.hide); // The better way: $( 'item1' ,  'item2' ,  'item3' ).invoke( 'hide' ); <<Back
  • 6. $$ $$(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. Sometimes the usual tools from your DOM arsenal – document.getElementById() encapsulated by $() , getElementsByTagName() and even Prototype’s very own getElementsByClassName() extensions – just aren’t enough to quickly find our elements or collections of elements. If you know the DOM tree structure, you can simply resort to CSS selectors to get the job done. Performance: when better alternatives should be used instead of $$ Now, this function is powerful, but if misused, it will suffer performance issues. So here are a few guidelines:   If you’re just looking for elements with a specific CSS class name among their class name set, use Prototype’s document.getElementsByClassName() extension. Better yet: if this search is constrained within a given container element, use the Element.getElementsByClassName() extension.
  • 7. Those methods should be favored in the case of simple CSS-class-based lookups, because they’re, at any rate, faster than $$ . On browsers supporting DOM Level 3 XPath, they’re potentially blazing fast.  Now, if you’re going for more complex stuff, indeed use $$ . But use it well. The $$ function searches , by default, the whole document . So if you can, scope your CSS rules as early as you can, e.g. by having them start with ID selectors. That’ll help reduce the search tree as fast as possible, and speed up your operation. Examples $$ ('div') // -> all DIVs in the document.  Same as document.getElementsByTagName('div')!   $$ ( ' #contents ' ) // -> same as $('contents'), only it returns an array anyway.   $$ ('li.faux') // -> all LI elements with class 'faux'   $$ ( ' #contents a[rel] ' ) // -> all links inside the element of ID &quot;contents&quot; with a rel attribute   $$ ('a[href=&quot;#&quot;]') // -> all links with a href attribute of value &quot;#&quot; (eyeew!)   $$ ( ' #navbar li' , ' #sidebar li ' ) // -> all links within the elements of ID &quot;navbar&quot; or &quot;sidebar&quot;
  • 8. Supported CSS syntax The $$ function does not rely on the browser’s internal CSS parsing capabilities (otherwise, we’d be in cross-browser trouble…), and therefore offers a consistent set of selectors across all supported browsers. The flip side is, it currently doesn’t support as many selectors as browsers that are very CSS-capable.   Here is the 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=&#8221;Hello World!&#8221;])   Class selector: CSS class names, as in .highlighted or .example.wrong. ID selector: as in #item1.   However, it currently does not support child selectors (>), adjacent sibling selectors (+), pseudo-elements (e.g. :after) and pseudo-classes (e.g. :hover). <<Back
  • 9. $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. The primary use of $A() is to obtain an actual Array object based on anything that could pass as an array (e.g. the NodeList or HTMLCollection objects returned by numerous DOM methods, or the predefined arguments reference within your functions). The reason you would want an actual Array is simple: Prototype extends Array to equip it with numerous extra methods, and also mixes in the Enumerable module, which brings in another boatload of nifty methods. Therefore, in Prototype, actual Arrays trump any other collection type you might otherwise get. The conversion performed is rather simple: null, undefined and false become an empty array; any object featuring an explicit toArray method (as many Prototype objects do) has it invoked; otherwise, we assume the argument &quot;looks like an array&quot; (e.g. features a length property and the [] operator), and iterate over its components in the usual way.
  • 10. Examples The well-known DOM method document.getElementsByTagName() doesn't return an Array, but a NodeList object that implements the basic array &quot;interface.&quot; Internet Explorer does not allow us to extend Enumerable onto NodeList.prototype, so instead we cast the returned NodeList to an Array: var  paras =  $A (document.getElementsByTagName( 'p' )); paras.each(Element.hide); $(paras.last()).show(); Notice we had to use each and Element.hide because $A doesn't perform DOM extensions, since the array could contain anything (not just DOM elements). To use the hide instance method we first must make sure all the target elements are extended: $A (document.getElementsByTagName( 'p' )).map(Element.extend).invoke( 'hide' ); Want to display your arguments easily? Array features a join method, but the arguments value that exists in all functions does not inherit from Array. So, the tough way, or the easy way? // The hard way... function  showArgs() {    alert(Array.prototype.join.call(arguments,  ', ' )); }   // The easy way... function  showArgs() {    alert( $A (arguments).join( ', ' )); } <<Back
  • 11. $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. <<Back
  • 12. $H $H([obj]) -> EnumerableHash The only way to obtain a hash (which is synonymous to “map” or “associative array” for our purposes). Returns a new object featuring all the methods in the Hash and Enumerable modules. If an original object was passed, clones all its properties in the result before mixing in the modules. The $H function is the only proper way to obtain a hash. Indeed, Hash is a module, not a class participating in Prototype’s class mechanism: doing a new Hash() is not going to help much: it will raise a ”Hash is not a constructor” error. The Hash module is designed to be mixed into objects that also mix in Enumerable, so the $H function makes sure it provides you with a result object that mixes in both of those. You can call $H() without any argument: you’ll obtain an “empty” hash (one that only features the methods in the mixed-in modules). If you pass it an argument, it starts by cloning out the passed object before mixing the modules in. Any property from that object whose name conflicts with a method in the modules will therefore get erased. <<Back
  • 13. $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. ObjectRange instances represent a range of consecutive values, be they numerical, textual, or of another type that semantically supports value ranges. See the type’s documentation for further details, and to discover how your own objects can support value ranges. The $R function takes exactly the same arguments as the original constructor: the lower and upper bounds (value of the same, proper type), and whether the upper bound is exclusive or not. By default, the upper bound is inclusive.
  • 14. Examples $R ( 0 ,  10 ).include( 10 ) // -> true   $A ( $R ( 0 ,  5 )).join( ', ' ) // -> '0, 1, 2, 3, 4, 5'   $A ( $R ( 'aa' ,  'ah' )).join( ', ' ) // -> 'aa, ab, ac, ad, ae, af, ag, ah'   $R ( 0 ,  10 ,  true ).include( 10 ) // -> false   $R ( 0 ,  10 ,  true ).each( function (value) {    // invoked 10 times for value = 0 to 9 }); Note that ObjectRange mixes in the Enumerable module: this makes it easy to convert a range to an Array ( Enumerable provides the toArray method, which makes the $A conversion straightforward), or to iterate through values. Note, however, that getting the bounds back will be more efficiently done using the start and end properties than calling the min() and max() methods. <<Back
  • 15. $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). This is one of those life-savers for people who just hate commas in literal arrays. Examples $w( 'apples bananas kiwis' ) // -> ['apples', 'bananas', 'kiwis']   This can slightly shorten code when writing simple iterations:   $w( 'apples bananas kiwis' ).each( function (fruit){    var  message =  'I like '  + fruit    // do something with the message })   This also becomes sweet when combined with Element functions:   $w('ads navbar funkyLinks').each(Element.hide); <<Back
  • 16. 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. This method provides a simple idiom for trying out blocks of code in sequence. Such a sequence of attempts usually represents a downgrading approach to obtaining a given feature.   In this example from Prototype's Ajax library, we want to get an XMLHttpRequest object. Internet Explorer 6 and earlier, however, does not provide it as a vanilla JavaScript object, and will throw an error if we attempt a simple instantiation. Also, over time, its proprietary way evolved, changing COM interface names. Try.these will try several ways in sequence, from the best (and, theoretically, most widespread) one to the oldest and rarest way, returning the result of the first successful function. If none of the blocks succeeded, Try.these will return undefined, which will cause the getTransport method in the example below to return false, provided as a fallback result value.
  • 17. getTransport:  function () {    return  Try.these(      function () {  return   new  XMLHttpRequest() },      function () {  return   new  ActiveXObject( 'Msxml2.XMLHTTP' ) },      function () {  return   new  ActiveXObject( 'Microsoft.XMLHTTP' ) }    ) ||  false ; } <<Back
  • 18. 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. Note that each returned element has been extended.
  • 19. Example HTML:    <body>      <div id=&quot;one&quot; class=&quot;foo&quot;>Single class name</div>      <div id=&quot;two&quot; class=&quot;foo bar thud&quot;>Multiple class names</div>      <ul id=&quot;list&quot;>        <li id=&quot;item_one&quot; class=&quot;thud&quot;>List item 1</li>        <li>List item 2</li>        <li id=&quot;item_two&quot; class=&quot;thud&quot;>List item 3</li>      </ul>    </body>   JavaScript:    document.getElementsByClassName( 'foo' ); // -> [HTMLElement, HTMLElement] (div#one, div#two)      document.getElementsByClassName( 'thud' ); // -> [HTMLElement, HTMLElement, HTMLElement] (div#two, li#item_one, li#item_two);      document.getElementsByClassName( 'thud' , $( 'list' ));    // -> [HTMLElement, HTMLElement] (li#item_one, li#item_two)   <<Back