$$ :: Utility Methods |
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:
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 "contents" with a rel attribute
$$('a[href="#"]') // -> all links with a href attribute of value "#" (eyeew!)
$$('#navbar li', '#sidebar li') // -> all links within the elements of ID "navbar" or "sidebar"
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:
If the value you’re matching against includes a space, be sure to enclose the value in quotation marks. ([title=”Hello World!”])
However, it currently does not support child selectors (>), adjacent sibling selectors (+), pseudo-elements (e.g. :after) and pseudo-classes (e.g. :hover).
|
Prototype API 1.5.0 - prototypejs.org