The difference in this case is:
-
$
returns an object
-
$$
returns a collection (type array) with an object.
What are these methods'?
$('teste') === $$('#teste')[0] // true
$('teste') === document.getElementById('teste') // true
$ or document.id
In MooTools $('id')
is the document.getElementById()
.
The method accepts a string that must be the ID of an element. This method always gives an object. If you do not find any return null
.
Can be used in $('id')
or even document.id('id')
(more secure not to create incompatibilities with other libraries).
$$
$$
is the method corresponding to the native document.querySelectorAll
, with more extras. For most browsers prior to .querySelectorAll
, it combines other native methods to search for elements in the DOM. This method always returns an array / collection of elements and accepts CSS selectors. The MooTools (Slick) search engine accepts a few more selectors such as div !> ul
, which is an inverse selector of >
.
If $$
(double dollar) does not find any elements of the DOM it returns an empty array. Attention that []
has a Boolean value true
, so using $$ must match with .length
if we want to have a boolean search.
Performance
The $ (or document.id) method is the simpler of the two. But since $$ allows CSS selectors and $
is only for IDs they work differently. Regarding the performance I've been testing now on IE, Firefox and Chrome and give different results. In IE wins the $ and in others the $$ m, all with differences below 5% ... I conclude that they are +/- similar.
Note: Since MooTools is a library that extends prototype you can also native methods combined with MooTools and it gets much faster there.
Test $ vs $$: link
In practice:
Search for content of <div id="id">Conteúdo</div>
:
var conteudo = $('id').get('html'); // dá-me "Conteúdo"
var conteudo = document.getElementById('id').get('html'); // dá-me "Conteúdo"
var conteudo = document.getElement('#id').get('html'); // dá-me "Conteúdo"
var conteudo = $$('#id').get('html'); // dá-me ["Conteúdo"]
Related:
In Mootools there is still another method: document.getElement
, it has the $$
functionalities but returns an object like $
, the first one to find.
Also related: a Dimitar's answer in SOen