Mootools 1.2 Selectors
If you haven’t already, be sure and check out yesterday’s tutorial – Day 1 – Intro to the Library. There we cover how to install Mootools 1.2 and how to call your scripts within the domready event.
Welcome to day 2 of 30 Days of Mootools 1.2 Tutorials. In this tutorial, we are going to learn several methods to select HMTL elements. In many ways, this is the basis of what Mootools is most commonly used for. After all, to create an interactive user experience out of HTML elements, you first have to get your hands on them.
The Basics
$();
The $ function is the basic selector within Mootools. With it, you can select a DOM element by ID.
//selects the element with the ID 'body_wrap' $('body_wrap');
<div id="body_wrap"> </div>
.getElement();
.getElement(); extends $, allowing you to refine your selection. For example, you could select the ID body wrap with $, then select the first child anchor. .getElement(); only selects a single element and will return the first if there are multiple options. If you add a class name within .getElement();, you will get the first occurrence of an element with that class name, not an array of all elements. To select multiple elements, see getElements(); below.
//selects the first child anchor within the element with the ID 'body_wrap' $('body_wrap').getElement('a'); //selects the element with the ID 'special_anchor' within the element 'body_wrap' $('body_wrap').getElement('#special_anchor'); //selects the first child with the class 'special_anchor_class' within the element 'body_wrap' $('body_wrap').getElement('.special_anchor_class');
<div id="body_wrap">
<a href="#">anchor</a>
<a href="#">another anchor</a>
<a id="special_anchor" href="#">special anchor</a>
<a class="special_anchor_class" href="#">special anchor</a>
<a class="special_anchor_class" href="#">another special anchor</a>
</div>$$();
The $$ lets you quickly select multiple elements and places them into an array (a type of list that lets you manipulate, retrieve, and reorder the list in all sorts of ways). You can select elements by name (such as div, a, img) or an ID, and you can even mix and match. And as a reader pointed out, you can do a lot more with $$ than what we are covering here.
//all divs in the page $$('div'); //selects the element with the id 'id_name' and all divs $$('#id_name', 'div');
<div>
<div>a div</div>
<span id="id_name">a span</span>
</div>.getElements();
.getElements(); is similar to .getElement();, except it returns all elements that fit the criteria, placing them into an array. You can use .getElements(); just like you would use .getElement();.
//selects all child anchors within the element with the ID 'body_wrap' $('body_wrap').getElements('a'); //selects all children with the class 'special_anchor_class' within the element 'body_wrap' $('body_wrap').getElements('.special_anchor_class');
<div id="body_wrap">
<a href="#">anchor</a>
<a href="#">another anchor</a>
<a class="special_anchor_class" href="#">special anchor</a>
<a class="special_anchor_class" href="#">another special anchor</a>
</div>Including and Excluding Results with Operators
Operators
Mootools 1.2 supports several operators that allow you to further refine your selections. You can use operators within .getElements(); and include or exclude certain results. Mootools supports 4 operators, each of which can be used to select an input element by name:
- = : is equal to
- ^= : starts-with
- $= : ends-with
- != : is not equal to
//selects the input with the name 'phone_number' $('body_wrap').getElements('input[name=phone_number]');
//selects the input with a name beginning with phone $('body_wrap').getElements('input[name^=phone]');
//selects the input with a name ending in number $('body_wrap').getElements('input[name$=number]');
//selects the input which is not named address $('body_wrap').getElements('input[name!=address]');
<div id="body_wrap">
<input name="address" type="text" />
<input name="phone_number" type="text" /> <!-- all four examples would select this element -->
</div>To use the operators, first define the element type (input), then define the attribute you would like to filter by (name), place your operator, then choose your filter string.
Selectors based on Element Order
even
Use this simple selector to choose evenly ordered elements. Note: this selector starts at 0, so the first element is even.
// selects all even divs $$('div:even');
<div>Even</div><!-- above example would select this element --> <div>Odd</div> <div>Even</div><!-- above example would select this element --> <div>Odd</div>
odd
Just like even, except this one selects all odd elements.
// selects all odd divs $$('div:odd');
<div>Even</div> <div>Odd</div><!-- above example would select this element --> <div>Even</div> <div>Odd</div><!-- above example would select this element -->
.getParent();
With .getParent(); you can get, well, the parent of an element.
// selects the parent of the element with the ID 'child_id' $('child_id').getParent();
<div id="parent_id"> <!-- The above would return this element -->
<div id="child_id">Even</div>
</div>Examples
Any Mootools UI development is going to start with selectors. Here are some very simple examples of how to use selectors to manipulate DOM elements.
//set the background color of all spans to #eee $$('span').setStyle('background-color', '#eee'); //set the background color of all odd children of #body_wrap to #eee $$('span:odd').setStyle('background-color', '#eee'); //sets the background color of all elements with class .middle_spans to #eee $('body_wrap').getElements('.middle_spans').setStyle('background-color', '#eee');
<div id="body_wrap">
<span>Even</span>
<span class="middle_spans">Odd</span>
<span class="middle_spans">Even</span>
<span>Odd</span>
</div>Download the zip and try it out
Here is a zip folder with a simple html file, the mootools 1.2 core, an external js file and the example you see above.
To Learn More…
This is by no means an exhaustive list of Mootools 1.2 selectors, rather it is intended to get you started and to give you an idea of what Mootools has to offer. To learn more about selectors, check out some of the following areas within the docs:
Mootools Blog Entry about $$ Selectors
Here is a great blog entry at mootools.net about the $$ selector and how diverse it is. You can do an incredible amount with this selector, and it’s worth taking a look.
Slickspeed Selectors
Here is an experiment from the folks over at Mootools that measures how fast different libraries are able to retrieve elements. This is cool unto itself, but more valuable are all the selector examples they have there. All of the selectors featured there should work with $$.
W3C Selectors
Mootools also lets you leverage the power of pseudo selectors (as demonstrated by slickspeed). Here is the w3c’s entry on selectors, definitely worth a read over (if only for the list of selectors available to you). I am not sure if every single selector on this page is supported by the $$ Mootools selector, but most are. Would love to hear if anyone knows more details on this.
Tomorrow’s Mootools 1.2 Tutorial
Be sure and check out tomorrow’s tutorial – Day 3 – Using Arrays.
Tutorial Request or Questions
We still have 28 days to go and I would love to hear what subjects are of the most interest to you all. Feel free to drop a note with any suggestions, comments or questions. Thanks and I hope you find this useful.
Tags: 30 days of mootools, javascript, Mootools 1.2, selectors, tutorials
Keep up the good work, these are very good tuts, looking forwad for the other 28 :-p
[...] to further refine your selection. Includes example and additional links to continue your learning. View source Posted in : General Post statistics : 1 [...]
I don’t think I am getting something. I am trying to follow along, but I am not getting results. One thing that wasn’t made clear (but I assumed) is that you should put the dom ready and mootools jazz inside script tags in the head of the document? Correct?
I know it is tons to ask, but maybe every now and again you can have a live demo so we can check your source code against ours.
Thanks a TON for this resource! I already know it is gonna kick some major tail!
Here is my code:
———————————————–
MooTools
[code]
window.addEvent('domready', function() {
//set the background color of all spans to #eee
$$('span').setStyle('background-color', '#eee');
//set the background color of all odd children of #body_wrap to #eee
$$('#body_wrap:odd').setStyle('background-color', '#eee');
//sets the background color of all elements with class .middle_spans to #eee
$('body_wrap').getElements('.middle_spans').setStyle('background-color', '#eee');
});
[/code]
Even
Odd
Even
Odd
————————————-
obviously my code didn’t come out right…so ignore that part
This is great!
If I could request some material to cover, I would suggest totally creating Mootools examples of Nick La’s jQuery application for designers (http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/). Especially, 1, 5a, 6, 7 & 10. Thanks! This is a wonderful service.
Peace
@2 – Looks like it was due to a mistake in my syntax, thanks for catching that Vin. I have also included a zip with everything you need to get started right under the example. Hope this makes it easier.
@4 – Thanks for the suggestions bejamin, I’ll be sure to include some of those later down the line after we get past the basics.
keep in mind that $$ is a ‘magic’ function that does much more… check out the docs for example…
//Creates an array of all elements and selectors passed as arguments.
$$(myelement1, myelement2, ‘a’, ‘#myid, #myid2, #myid3′, ‘tr:odd’, document.getElementsByTagName(‘div’));
Thanks Tom. Yeah, $$ covers a lot of ground and is very powerful. Here is a link to that section within the docs: http://docs.mootools.net/Element/Element#dollars
This is great. I’ve been wanting to learn MooTools and eventually some jQuery too. So far so good. Everything really makes sense! =)
Actually…and maybe this will come later but can someone explain that example from docs regarding $$?
The one that Tom mentioned:
//Creates an array of all elements and selectors passed as arguments. $$(myelement1, myelement2, ‘a’, ‘#myid, #myid2, #myid3′, ‘tr:odd’, document.getElementsByTagName(‘div’));
Very interesting again, just like yesterday. The level is going up very good I think. You explain the things clear and it’s easy to understand. Thanks!
np Brian – $$ creates an array and the various selectors choose what goes in that array. $$ accepts many types of selectors, and can mix and match. For example the first two (myelement1 and myelement2) are VARIABLES that “contain” elements (this idea of variables is something we are going to dig into within the next few tutorials). The next one (‘a’) is an element TAG selector. ‘a’ in this case is the “anchor” tag, but you could use ‘div’ or ’span’ or any other element tag. The next three (#myid, #myid2, #myid3) are elements IDs. The next one uses the “odd” selector to add all odd “tr” elements to the array. The last one is a javascript selector, first it is grabbing the “document” (which is essentially the html page), then it “gets element by tag name,” in this case, ‘div.’ The last example could have been accomplished by simply saying ‘div,’ but its in the example to show that it accepts javascript arguments. Hope this answers your question.
Thanks Troy! That was very helpful and makes sense. So now I’m wondering, what does that allow you to do? Does that mean with the array it has created, you can now right some kind of a script allowing you to alter everything you selected?
Exactly, Brain. Just like in the example above, you could add .setStyle(‘background-color’, ‘#eee’); to the $$ selector, and it would change all elements within that array to background-color: #eee;. We are going to dig into the various things you can do with selectors (like setStyle) as we progress through the series.
That IS pretty powerful. I could see much value in something like this especially if you have an existing site that you need to make site-wide changes to. Awesome. Thanks again Troy!
Could you write something about performance issues with the mootools. Cause every element extends with the Element methods using an mootools selector have to trash by mootools in the onunload event. This can be very problematic when the selector is used very often, for example all cells of a table.
@15 We aren’t really getting into that depth at this point in the tutorials (as we are trying very hard to keep this as simple and approachable as possible). Perhaps we could do a tutorial later in the series about how to avoid performance issues with Mootools. Would love to hear any input you have on the subject.
I would just like to thank you guys for going thru the basics. I have been using mootols for a couple of months now and it has been a struggle to understand by just looking at the code. So for me this helps a lot. thanx!
[...] 30 Days of MooTools 1.2 Tutorials – Day 2 – Selectors [...]
@Troy,
I love the tutorials, as I am having a very hard and frustrating time getting the simplest things working with mootools.
You said “you could add .setStyle(‘background-color’, ‘#eee’); to the $$ selector, and it would change all elements within that array to background-color: #eee;.”
But exactly this is not working at all for me.
I have this code :
$$(‘#test3′).setStyle(‘background-color’, ‘#eee’);
and in my html page two div’s with the ID test3
the code is only changing the first div it finds, not all.
ultimately I’m trying to hide and show table rows based on criteria, but as I said, the simplest things are not working for me.
I have gone through the whole Internet three times already, trying every possible combination (each… etc) but I’m fundamentally missing something that keeps me from understanding how this works.
Could you please provide an example of how you have this working ?
Likewise :
$(‘test2′).getElements(‘#test1′).fade(‘out’);
only fades the first element with ID test1, but your tutorial specifically sais it should apply to all IDs.
I’m stumped and getting desperate, I have been trying to find a solution for this for over a week now, and doing exactly what you describe…
By using #, you are using ID’s, and you are only suppose to have one id per page. Try using $$(‘div’) or $$(‘.className’) instead.
Hi Troy,
I couldn’t have been any stupider… I think I must get more sleep.
indeed ID’s should be unique.
Thanks for the reply. On to tutorial 3.
[...] Introducción a los arrays en Mootools 1.2 Si no lo has hecho todavía, asegúrate de chequear el tutorial correspondiente al dia 2. [...]
[...] Vía | ConsiderOpen [...]
[...] Introducción a los arrays en Mootools 1.2 Si no lo has hecho todavía, asegúrate de chequear el tutorial correspondiente al dia 2. [...]
[...] Vía | ConsiderOpen [...]
I think for the sake of ASP.NET web controls you all should consider supporting *= in your operators. For now I’ll hold onto jQuery…
I see that MooTools wins the race at Slickspeed, but I think that may be because all the MooTools tests fail.
this is very useful thanks for this wonderful tuts.
var i = 1;
var line1 = $(‘itmQty’+i)
Can this be done? I get errors when doing this.
another way to do this?
var itemQty = 2;
var i = 1;
var line_1 = itemQty + i;
alert(line_1);
//alert will product ‘3′
is this what you are going for ranail?
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
[...] Selectors [...]
Excelent … in google I hadn’t found the method $$() for mootools, and you explained that well … I should say: perfect.