Java Reference
In-Depth Information
By doing this, you can use both native DOM methods and properties as well as the methods provided
by Prototype.
Prototype's dollar function returns null if the specifi ed element cannot be found. This is unlike
jQuery's $() function because Prototype returns an extended DOM element object; even though it is
extended, it is still a DOM element object.
Selecting Elements With CSS Selectors
Another difference between Prototype's dollar function and jQuery's $() function is that it does not
accept CSS selectors; it only accepts element id values and Element objects. Prototype does, however,
have another function that behaves similarly to jQuery's $() function, and that is the $$() function.
You can pass several selector types to the $$() function to locate and retrieve elements that match the
selector. For example, the following code retrieves all <div/> elements in the page and returns them in
an array, so you can use the length property:
$$(“div”)
The $$() function always returns an array, so even if you use an id selector, you'll get an array with
one element in it if the element is found. One downside to the double dollar function is that it returns
an array of extended elements. If you want to perform an operation on every element in the array, you
have to either loop through them or iterate over them with the Prototype-provided each() method.
Performing an Operation on Elements Selected With $$()
The each() method is similar to the new Array.every() method you learned about in Chapter 5. It
accepts a function as a parameter and executes that function on every element in the array. The follow-
ing code demonstrates this:
function insertText(item)
{
item.insert(“This text inserted using the each() method.”);
}
$$(“div”).each(insertText);
The jQuery object also has an each() method that performs the same function.
You can use several CSS selector types to select elements with the double dollar function, and you can
select elements based upon multiple selectors, although it is different from how you did it with jQuery.
$$(“#myDiv”, “p > span, .myCssClass”);
Instead of passing one string with commas separating each selector, you pass multiple strings with
each string containing one selector. Once you retrieve an element (or elements), you can then begin to
manipulate them, such as changing their style.
For more information on the CSS selector supported in Prototype, see http://www.prototypejs.org/
api/utility/dollar-dollar .
Search WWH ::




Custom Search