Eight Weeks of Prototype: Week 1, Beginning with Prototype
The $$() Function
One of the most powerful functions provided by Prototype is the
$$() function. This function allows you to select a series of elements from the DOM by using CSS selectors. The value returned from calling
$$() is an array containing each found element, in the order each element appears in the HTML document.
To better demonstrate how
$$() works, here are some examples:
$$('img')- select all image elements in a document.
$$('#container a')- select all links within the element that has the ID
$$('div.someClass input[type=submit]')- retrieve all submit buttons inside a div with the class
If no matching elements are found then an empty array is returned.
Listing 5 shows an example of using
$$(). In this example we loop over the returned elements and write a number to each element. In the third article in this Prototype article series we will see an easier way to loop over arrays, but for now a simple
for loop will suffice.
size()method to determine the number of elements in the array. This is extended functionality for arrays provided by Prototype. This is covered more extensively in the third article of "Eight Weeks of Prototype".
As a general rule of thumb,
$$() is much more efficient when the selection is qualified by including an element ID at the start. For example, if you want to find all elements in the document with the class of
someClass and you know all of these occur within an element with ID
someId, it is more efficient to use
$$('#someId .someClass') rather than
$$('.someClass'). The reason the search is more efficient is because rather than checking the class of every element in the DOM, only elements within
#someId need to be checked.
When using the
$$() function, you can provide more than one argument if required. This allows you to select elements based on multiple CSS selectors. Regardless of which selector is used to find an element, all elements are returned in a single array in document order (just as when using a single argument).
The select() Method
One of the extended methods provided by Prototype is the
() method (formerly called
getElementsBySelector()). Just like the
$$() function, this method accepts one or more CSS selectors as arguments, however the key difference between
$$() is that
select() only searches within the element on which it is called.
In the previous section, I discussed including an element's ID in
$$() to speed up the search. The example given was to use
$$('#someId .someClass'). The equivalent of this search using
select() would be to use
Listing 6 shows an example of using
select() rather than using
$$(). You will find
select() most useful when writing classes or functions to which an element has been passed in which you want to find specific elements.