Selecting DOM Elements using MooTools 1.2: Part 1

Exclusive offer: get 50% off this eBook here
MooTools 1.2 Beginner's Guide

MooTools 1.2 Beginner's Guide — Save 50%

Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework

$23.99    $12.00
by Jacob Gube | December 2009 | Java Open Source

In this article by Jacob Gube, we will look at:

  • The $() and $$() function
  • Selecting HTML elements with pseudo-class selectors
  • Selecting HTML elements based on their attributes

So let’s get on with it...

In order to successfully and effortlessly write unobtrusive JavaScript, we must have a way to point to the Document Object Model (DOM) elements that we want to manipulate. The DOM is a representation of objects in our HTML and a way to access and manipulate them. In traditional JavaScript, this involves a lot (like, seriously a lot) of code authoring, and in many instances, a lot of head-banging-against-wall-and-pulling-out-hair as you discover a browser quirk that you must solve.

Let me save you some bumps, bruises, and hair by showing you how to select DOM elements the MooTools way. This article will cover how you can utilize MooTools to select/match simple (like, "All div elements") up to the most complex and specific elements (like, "All links that are children of a span that has a class of awesomeLink and points to http://superAwesomeSite.com

MooTools and CSS selectors

MooTools selects an element (or a set of elements) in the DOM using CSS selectors syntax.

Just a quick refresher on CSS terminology, a CSS style rule consists of:

selector {
property: property value;
}
  • selector: indicates what elements will be affected by the style rule.
  • property: the CSS property (also referred to as attribute). For example, color is a CSS property, so is font-style. You can have multiple property declarations in one style rule
  • property value: the value you want assigned to the property. For example, bold is a possible CSS property value of the font-weight CSS property.

For example, if you wanted to select a paragraph element with an ID of awesomeParagraph to give it a red color (in hexadecimal, this is #ff0), in CSS syntax you'd write:

#awesomeParagraph {
color: #ff0;
}

Also, if I wanted to increase its specificity and make sure that only paragraph elements that have an ID of awesomeParagraph is selected:

p#awesomeParagraph {
color: #ff0;
}

You'll be happy to know that this same syntax ports over to MooTools. What's more is that you'll be able to take advantage of all of CSS3's more complex selection syntax because even though CSS3 isn't supported by all browsers yet, MooTools supports them already. So you don't have to learn another syntax for writing selectors, you can use your existing knowledge of CSS - awesome, isn't it?

Working with the $() and $$() functions

The $() and $$() functions are the bread and butter of MooTools. When you're working with unobtrusive JavaScript, you need to specify which elements you want to operate on.

The dollar and dollars functions help you do just that - they will allow you to specify what elements you want to work on.

Notice, the dollar sign $ is shaped like an S, which we can interpret to mean 'select'.

The $() dollar function

The dollar function is used for getting an element by it's ID, which returns a single element that is extended with MooTools Element methods or null if nothing matches. Let's go back to awesomeParagraph in the earlier example. If I wanted to select awesomeParagraph, this is what I would write:

$('awesomeParagraph’)

By doing so, we can now operate on it by passing methods to the selection. For example, if you wanted to change its style to have a color of red. You can use the .setStyle() method which allows you to specify a CSS property and its matching property value, like so

$('awesomeParagraph').setStyle('color', '#ff0');

The $$() dollars function

The $$() function is the $() big brother (that's why it gets an extra dollar sign). The $$() function can do more robust and complex selections, can select a group, or groups of element’s and always returns an array object, with or without selected elements in it.

Likewise, it can be interchanged with the dollar function. If we wanted to select awesomeParagraph using the dollars function, we would write:

$$('#awesomeParagraph')

Note that you have to use the pound sign (#) in this case as if you were using CSS selectors.

When to use which

If you need to select just one element that has an ID, you should use the $() function because it performs better in terms of speed than the $$() function.

Use the $$() function to select multiple elements. In fact, when in doubt, use the$$() function because it can do what the $() function can do (and more).

A note on single quotes (') versus double quotes ("")
The example above would work even if we used double quotes such as $("awesomeParagraph") or $$("#awesomeParagraph") ") - but many MooTools developers prefer single quotes so they don’t have to escape characters as much (since the double quote is often used in HTML, you'll have to do "in order not to prematurely end your strings). It's highly recommended that you use single quotes - but hey, it's your life!

Now, let's see these functions in action. Let's start with the HTML markup first. Put the following block of code in an HTML document:

<body>
<ul id="superList">
<li>List item</li>
<li><a href="#">List item link</a></li>
<li id="listItem">List item with an ID.</li>
<li class="lastItem">Last list item.</li>
</ul>
</body>

What we have here is an unordered list. We'll use it to explore the dollar and dollars function. If you view this in your web browser, you should see something like this:

MooTools 1.2 Beginner's Guide

Time for action – selecting an element with the dollar function

Let's select the list item with an ID of listItem and then give it a red color using the .setStyle() MooTools method.

  1. Inside your window.addEvent('domready') method, use the following code:
    $('listItem').setStyle('color', 'red');
  2. Save the HTML document and view it on your web browser. You should see the 3rd list item will be red.

    MooTools 1.2 Beginner's Guide

  3. Now let's select the entire unordered list (it has an ID of superList), then give it a black border (in hexadecimal, this is #000000). Place the following code, right below the code the line we wrote in step 1:
    $('superList').setStyle('border', '1px solid #000000');
  4. If you didn't close your HTML document, hit your browser's refresh. You should now see something like this:

    MooTools 1.2 Beginner's Guide

Time for action – selecting elements with the dollars function

We'll be using the same HTML document, but this time, let's explore the dollars function.

  1. We're going to select the last list item (it has a class of lastItem). Using the .getFirst(), we select the first element from the array $$() returned. Then, we're going to use the .get() method to get its text. To show us what it is, we'll pass it to the alert() function. The code to write to accomplish this is:
    alert( $$('.lastItem').getFirst().get('text') );
  2. Save the HTML document and view it in your web browser (or just hit your browser's refresh button if you still have the HTML document from the preview Time for action open). You should now see the following:

    MooTools 1.2 Beginner's Guide

Time for action – selecting multiple sets of elements with the dollars function

What if we wanted to select multiple sets of elements and run the same method (or methods) on them? Let's do that now.

  1. Let's select the list item that has an <a> element inside it and the last list item (class="lastItem") and then animate them to the right by transitioning their margin-left CSS property using the .tween() method.
  2. Right below the line we wrote previously, place the following line:
    $$('li a, .lastItem').tween('margin-left', '50px');
  3. View your work in your web browser. You should see the second and last list item move to the right by 50 pixels.

    MooTools 1.2 Beginner's Guide

What just happened?

We just explored the dollar and dollars function to see how to select different elements and apply methods on them. You just learned to select:

  • An element with an ID (#listItem and #superList) using the dollar $() function
  • An element with a class (.lastItem) using the dollars $$() function
  • Multiple elements by separating them with commas (li and .lastItem)

You also saw how you can execute methods on your selected elements. In the example, we used the .setStyle(), .getFirst(), get(), and .tween() MooTools methods.

Because DOM selection is imperative to writing MooTools code, before we go any further, let's talk about some important points to note about what we just did.

MooTools 1.2 Beginner's Guide Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework
Published: December 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

$() versus document.getElementByID()

When we used the $() dollar function, it's equivalent to using the .getElementById() native JavaScript method. The difference is that using .getElementById() ends up with longer code and, in Internet Explorer, elements returned by .getElementById() are not extended with MooTools Element methods.

If we wanted to perform the same operation using JavaScript's .getElementById(),instead of:

$('listItem').setStyle('color', 'red');

We would first have to declare an object that will contain our desired DOM element like so:

var listItem = document.getElementById('listItem');

But we have to extend the element with MooTools Element methods, or else setStyle will not be available. So we’ll change the code a tiny bit:

var listItem = $(document.getElementById);

Then we'd pass the .setStyle() method on our object:

listItem.setStyle('color', 'red');

Can we all agree that we just saved a lot of typing and that we can worry less about browser issues that may occur using the .getElementById() method? I think we can!

Selecting multiple sets of elements

In Step 2 of Time for action – selecting multiple sets of elements with the dollars function, we selected two sets of elements using one $$() function; we matched all <a> tags inside a list item <li> and all elements with the class of lastItem.

What we did in step 3 is the same as writing:

$$('li a').tween('margin-left', '50px');
$$('.lastItem').tween('margin-left', '50px');

Because one of  MooTools key design principles is to avoid repeating yourself, you use $$() function if you will be performing the same operations on the sets of elements, by separating your selection strings with a comma (,).

You can have as many sets of elements as you want.

Have a go hero – tween the list item element

Here's a good point to modify the example we wrote together. Try adding the list item with an ID of lastItem to the set of elements that used the .tween() method to transition to the left. If you did it correctly, the third list item should also move to the left when you test the script.

MooTools 1.2 Beginner's Guide

Common errors with the dollar and dollars functions

When selecting elements using the $$() function, the syntax is exactly like CSS selectors. For example, if we wanted to select all <a> that are inside a list item <li> tag and give them a color of red, in CSS, we'd write:

li a {
color: red;
}

The same exact thing can be done in MooTools using the following line of code:

$$('li a').setStyle('color', 'red');

The dollar function doesn't work with CSS selectors!

Note the use of an exclamation point here - and you should pause here for a moment, close your eyes, and imagine me shouting this at the top of my lungs to make sure everyone hears it.

The $() function doesn't work with CSS selectors like the $$() function does because it only takes the ID name, and nothing else. CSS selectors can look like #awesomeParagraph, p#awesomeParagraph, or .lastItem.

A common mistake that beginning MooTool'ers make is trying to do this:

$('li a')

MooTools interprets the above line as:

"Select the element with the ID of ''li a'"

and not:

"Select all <a> elements that are inside a list item <li>" like we intended it to.

So what happens when you do this? If you don't have an element in your web page with the ID of li a", (which you shouldn’t because spaces are not allowed for ID’s as part of HTML standard spec), then $() will return null since an element with the id “li a” does not exist.

Drop the pound # sign when using the $() function

If you're going to use the $$() function to select an element with an ID of superList, you have to write:

$$('#superList')

Again, imagine you're writing CSS code, you wouldn't write:

superList {
border: 1px solid #000000;
}

Instead, you'd write:

#superList {
border: 1px solid #000000;
}

But when you're selecting an element by its ID using the $() function, always remember to leave out the pound # sign because, like I said earlier, the $() function doesn't work with CSS selectors.

For example, you'll be disappointed by a JavaScript error if you write this code:

$('#superList').setStyle('border', '1px solid #000000');

It won't work because you would be selecting an element with an ID name of #superList and not superList like you intended.

Pop quiz – find the bad apple in the bunch

Which of the following selection operations won't work?

  • $$('ul li a span')
  • $$('.myClass', 'p.indentedText', 'myID')
  • $('myID')
  • $("thisID")

Selection using pseudo-classes

MooTools' selection awesomeness is further awesome'ized in its ability to utilize pseudo-classes. Pseudo-class selectors are special selectors that allow you to find items from the DOM using properties that can't be easily deduced using ordinary ID, class, tag or attribute selectors. Psuedo-class selection will allow you to write complex selection strings, ones that would involve a ton of code if you were to write them in native JavaScript syntax.

A pseudo-class, in CSS3 specifications, allows you to select DOM elements that are difficult to select using normal selectors. The pseudo-class concept was introduced as part of CSS3 specifications by the W3C organization (the people in charge of establishing web standards).

Using a pseudo-class is simple, and follows the format:

:pseudo-classname

Or

:(pseudo-classname)

You can read more about the concept of pseudo-classes from the W3C CSS3 Selectors Level 3 Working Draft:
http://www.w3.org/TR/css3-selectors/#pseudo-classes

MooTools has a plethora of pseudo-class selectors that you can readily use such as the :contains() pseudo-class which searches for elements containing a certain string of text. For example, to find all paragraphs that have the text MooTools is l33t, you would write:

$$('p:contains(MooTools is l33t)')

If you're ever tried to write a similar piece of code using native JavaScript - you know exactly how much pseudo-classes will help you save some time and keep your sanity.

Pseudo-class example: zebra striping a table

Let's see what pseudo-class selection can do with an example. In the following section, we're going to "zebra stripe" an HTML table, which basically means we're going to make the rows of our table alternate between two colors. Zebra striping a table is usually done to make HTML tables with a lot of data more readable.

>> Continue Reading Selecting DOM Elements using MooTools 1.2: Part 2

 

MooTools 1.2 Beginner's Guide Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework
Published: December 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Jacob Gube

Jacob Gube is a massive MooTools developer. He is the Founder and Chief Editor of Six Revisions, a website dedicated to web developers and web designers. He's also written for other popular web publications such as Read Write Web and Smashing Magazine discussing web technologies and development. A web professional for 8 years, Jacob is an in-house web developer specializing in distance-learning education and web accessibility, using PHP, MooTools, and jQuery to get the job done.

Books From Packt

ADempiere 3.4 ERP Solutions
ADempiere 3.4 ERP Solutions

Beginning OpenVPN 2.0.9
Beginning OpenVPN 2.0.9

Funambol Mobile Open Source
Funambol Mobile Open Source

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

Tomcat 6 Developer's Guide
Tomcat 6 Developer's Guide

JBoss AS 5 Development
JBoss AS 5 Development

jBPM Developer Guide
jBPM Developer Guide

Apache CXF Web Service Development
Apache CXF Web Service Development

No votes yet
p#awesomeParagraph - IDs should be unique in a page by Christopher J. Erdal
Thanks for a useful primer, but I'd like to nit-pick just a little: IDs should be just that - unique identifiers on a page. If you are tempted to use the same ID for several items, it's better to use a classname instead. So your example: p#awesomeParagraph { color: #ff0; } might be misleading in terms of "best coding practice", as it implies that there could be several HTML items with the same ID.

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
X
k
e
a
y
m
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software