The Dollars Function

Sometimes you'll want to get an array or collection of elements based on some criteria. Most often, that would be a class name. There is no easy function getElementsByClass or at least not one we don't have to implement ourselves. MooTools has a function that takes care of that actually.

var myElements = $$(".breadcrumbs");

As you can see, the syntax for getting all of the elements by class is pretty clean.

Reasoning

In MooTools the $$ function is very powerful. Not only can it be used for finding elements with the same class, it can also be used with any CSS selector.

  • You can get collections of tags.
  • You can get collections of CSS Selected elements.
  • Easy to work with after collections are formed. (Explained Later.)

The Dollars Function Syntax

/*
  The Dollars Syntax
*/
 
// Simple
 
$$('a'); // Returns all anchor elements in the page
$$('a', 'b'); // Returns anchor and bold tags on the page
 
// The Examples Below require 'Selectors' to be in your mootools file.
 
$$('#myElement'); // Returns an array containing only the element with the id 'myElement'
 
$$('#myElement a.myClass'); // Returns an array of all anchor tags with the class 'myClass' within the DOM element with id 'myElement'
 
// Complex Example
$$('a', '#myid, #myid2, #myid3', document.getElementsByTagName('div')); // Returns an array of all selectors passed in, going from left to right.

As you can see, you can tell that this makes finding elements near each other simple and fast. MooTools' Selector Speed is currently in the top 3.

Notes

  • In order to use CSS Selectors you must include Selectors in your MooTools download.
  • If Selectors is not present in the download, only tag names will work. (Sadly.)
  • You can read about $$ in the Mootorial.
  • You can test out the Selector Speed At SlickSpeed.

Continue to DOM Events

 
walkthrough-1.2/the-dollars-function.txt · Last modified: 2009/02/21 04:27 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki