Selecting DOM Elements using MooTools 1.2: Part 2

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

Read Part One of Selecting DOM Elements using MooTools 1.2 here.

Time for action – using pseudo-classes to zebra stripe a table

Let's set up the markup for our HTML table - it'll have three columns and six rows listing my favorite movies in order.

Pseudo-class example HTML table markup:

<body>
<table width="100%" cellpadding="1" cellspacing="0">
<!-- column headings -->
<tr>
<th>Rank</th>
<th>Movie</th>
<th>Genre</th>
</tr>
<tr>
<td>1</td>
<td>The Matrix</td>
<td>Action</td>
</tr>
<tr>
<td>2</td>
<td>Die Hard</td>
<td>Action</td>
</tr>
<tr>
<td>3</td>
<td>The Dark Knight</td>
<td>Action</td>
</tr>
<tr>
<td>4</td>
<td>Friday</td>
<td>Comedy</td>
</tr>
<tr>
<td>5</td>
<td>Love Actually</td>
<td>Drama</td>
</tr>
</table>
</body>

Our HTML table should look like this:

MooTools 1.2 Beginner's Guide

  1. To color even rows with a light gray color, write this line of code (again, we use the .setStyle() method):
    $$('table tr:even').setStyle( 'background-color', '#ebebeb' );
  2. Save your work. View your document in a web browser. You should see something like this:

    MooTools 1.2 Beginner's Guide

  3. Now we're going to style the odd rows. This time, instead of .setStyle(), we're going to use the .setStyles() method so that we can supply more than one CSS property/CSS property value pair to be implemented. Here's the code to accomplish what we set out to do (which you can place right below the code in step 1):
    $$('table tr:odd').setStyles( {
    'background-color' : '#252525',
    'color' : '#ffffff'
    } );
  4. Save your work and view your work in a web browser. Your HTML table that contains my favorite movies of all time should now looks like this:

    MooTools 1.2 Beginner's Guide

What just happened?

We just learned one of the many ways where pseudo-class selectors are helpful. In this case, we took a regular HTML table and zebra striped it so that we have different styles at alternating rows.

To zebra stripe our HTML table, we used the :even and :odd pseudo-class selectors to change the background color of even row with a light gray color (#ebebeb in hexadecimal) and all odd rows of our tables with a dark gray background (#252525) with a white foreground color (#ffffff).

A couple of notes on the :odd and :even pseudo-class selectors
The :odd and :even pseudo-classes aren't available in W3C specifications; although the concept of using them is the same, they are custom MooTools pseudo-class selectors.
Secondly, the index of each one starts at 0. Because of this, using :even would select the first element  (index 0) and third child elements because their index is actually 0 and 2, respectively. So they're kind of switched around in the conventional sense of odd and even.

Other Pseudo-class selectors

There are nine MooTools pseudo-class selectors as of version 1.2:

Pseudo-class Selector

Description

:contains

Matches elements that contain a particular text string.

For example, matching all <div>'s with the text "I love MooTools" is $$('div:contains(I love MooTools)')

:empty

Matches elements that don't contain anything.

For example, $$(div:empty) would match this: <div></div>

:enabled

Matches elements that are enabled. Usually used in <input> tags.

:even

Matches all child elements that have an even index.

For example, if there are four paragraphs, using $$('p:even') would select the first and third paragraphs (remember that the index starts at 0).

:first-child

Matches the first child element (i.e. the child with an index of 0).

For example, if there are four paragraphs in a <div> element, using $$('div p:first-child') would select the first paragraph inside the <div> element.

:last-child

Matches the last child element (i.e. the child with the highest index).

For example, if there are four paragraphs in a <div> element, using $$('div p:last-child') will select the fourth paragraph inside the <div> element.

:not

Matches elements that do not match a particular selector.

For example, matching all paragraphs that do not have the class .intro would be $$('p:not(.intro)').

:nth-child

Matches the nth expression child element. You can use mathematical expressions.

For example, $$('div:nth-child(3n+1)') would select the first div (3(0)+1 = index 0 position), 4th div (3(1)+1 = index 4 position)... 3(n)+1 index position.

You can also use, as an argument: even, odd, first, and last as in div:nth-child(even) which is exactly like the :even pseudo-class selector.

:odd

Matches all child elements with an odd index.

For example, If there are four paragraphs, using $$('p:odd') would select the second paragraph and fourth paragraph (index 1 position and index 3 position).

:only-child

Matches all elements that are the only children of  the only child element.

For example, $$(p:only-child) would match the paragraph <div><p>only child></p></div> but will not match these paragraphs <div>><p>not an only child></p>><p>not only child></p></div> because it has a sibling paragraph.

Working with attribute selectors

If you thought MooTools can't get any cooler with element selection - well, it gets much better. MooTools also implements CSS3's Attribute Selectors. An Attribute Selector allows you to select elements based on their CSS attributes, also commonly referred to as properties in MooTools.

For example, an <input> tag's type is considered one of its attributes (or properties), so is its class

<input type=”text” name=”query” value=”” />

In MooTools (as well as CSS3), the syntax for an attribute selector is as follows:

element[attribute=attribute value]

For example, if we wanted to select all <input> elements with a type of text, we would write:

$$('input[type=text]');

Attribute selector operators

Attribute selectors can match attribute values various ways using Attribute selector operators. The following table depicts a list and description of each attribute selector operator.

Operator

Description

=

Matches attribute value exactly and literally.

For example, $$('a[class=myLinkClass]') will match all <a> elements with the class of myLinkClass.

!=

Matches all elements with the attribute value that is not the value given.

For example, $$('a[class!=myLinkClass]') will select all <a> elements that doesn't have the class of myLinkClass.

^=

Matches all elements with attribute value that starts with the value given.

For example, $$('img[src^=big]') will match all images with the src attribute value the begins with the word big, such as big-picture.png or biggiesmalls.jpg.

$=

Matches all elements with the attribute value that ends with the value given.

For example, $$('img[src$=.jpg]') will select all images that end with .jpg - useful in selecting particular file extensions.

Attribute Selector example: styling different types of links

Often, you want to indicate to a user what a particular type of link is. For example, you may want to indicate to the user that a particular link goes to another website or that a link is a mailto: link that will open up their default email client. Perhaps, you want to highlight all links that point to a particular domain name like sixrevisions.com.

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:

Time for action – using = attribute selector

Let's see exactly what attribute selectors can do. In the following HTML markup, you'll see a variety of links. Just pop this into an HTML document and we'll be good to go:

<body>
<p>Go to the <a href="http://mywebsite.com">home page</a>.</p>
<p><a href="http://mywebsite.com/about">This link</a> will not go
to the home page.</p>
<p>Please <a href="mailto:jacob@mywebsite.com">email me </a>or
<a href="mailto:matt@mywebsite..com">email Matt</a>.</p>
<p>Download this <a href="foo.zip">ZIP file</a>.</p>
</body>

You should have something like this:

MooTools 1.2 Beginner's Guide

Let's style the first link with MooTools. Its href attribute goes to http://mywebsite.com. Let's say that we want all links in our web page that point to the site's home page will have a green color. We'll use the .setStyle() method to apply the style.

  1. To select all links in a web page that have the href attribute of http://mywebsite.com,we write:
    $$('a[href="http://mywebsite.com"]').setStyle('color', '#7cc576');
  2. Open up your HTML document in a web browser. You should see that the first link is now green:

    MooTools 1.2 Beginner's Guide

  3. Your JavaScript should look like this at this point:

    <script type=”text/javascript”>
    window.addEvent(‘domready’, function(){
    $$('a[href="http://mywebsite.com"]').setStyle('color', '#7cc576');
    });
    </script>

Time for action – using != attribute selector

Now, continuing with our example, we should try out the Not (!=) attribute selector. We're going to color all of the links in the web page that doesn't point to the home page red (#9e0b0f).

  1. To color all links that don’t go to http://mywebsite.com, we write this after our previous line of JavaScript:
    $$('a[href!="http://mywebsite.com"]').setStyle('color',
    '#9e0b0f');
  2. Save your work and open or refresh your web browser to view what our HTML document looks like now. You should see something like this:

    MooTools 1.2 Beginner's Guide

  3. Your JavaScript should look like this at this point:
    <script type="text/javascript">
    window.addEvent('domready', function(){
    $$('a[href="http://mywebsite.com"]').setStyle('color', '#7cc576');
    $$('a[href!="http://mywebsite.com"]').setStyle('color',
    '#9e0b0f');
    });
    </script>

Time for action – using ^= attribute selector

For all hyperlinks that have the mailto: attribute value inside its href attribute, let's make their underline dashed, and then give them a light blue color. This can give users a visual clue that the link they're going to be clicking on will open up their default email client.

Since we have to set multiple CSS properties, we'll use the .setStyles() method.

  1. To select all links that start with the mailto: value in its href attribute, we write the following after our previous line of JavaScript:
    $$('a[href^=mailto:]').setStyles({
    // Remove link underline first
    'text-decoration' : 'none',
    // Add a dashed bottom border
    'border-bottom' : '1px dashed #9e0b0f',
    // Set background color
    'background-color' : '#7da7d9'
    });
  2. Open or refresh your HTML document. If all went according to plan, you should see the two links with the mailto: attribute styled in a similar fashion, as the screenshot below:

    MooTools 1.2 Beginner's Guide

  3. Your JavaScript should look like this at this point:
    <script type="text/javascript">
    window.addEvent('domready', function(){
    $$('a[href="http://mywebsite.com"]').setStyle('color', '#7cc576');

    $$('a[href!="http://mywebsite.com"]').setStyle('color',
    '#9e0b0f');

    $$('a[href^=mailto:]').setStyles({
    // Remove link underline first
    'text-decoration' : 'none',
    // Add a dashed bottom border
    'border-bottom' : '1px dashed #9e0b0f',
    // Set background color
    'background-color' : '#7da7d9'
    });

    });
    </script>

Time for action – using $= attribute selector

Let's give the link that points to a ZIP file a different font style and a gray border by utilizing the $ = attribute selector. This can be helpful in distinguishing links that will prompt the user to download a file from a web page.

  1. In order to give links that point to a ZIP file a different style, use the $ = as follows, after the previously entered JavaScript code:
    $$('a[href$=.zip]').setStyles({
    // Remove link underline first
    'text-decoration' : 'none',
    // Assign a different font style
    'font' : 'bold 14px "Courier New"',
    // Give them some padding
    'padding' : 2,
    //Add a solid gray border around the link
    'border' : '1px solid #898989',
    });
  2. Open or refresh your web browser and you should see something like this:

    MooTools 1.2 Beginner's Guide

  3. Your JavaScript should look like this at this point:
    <script type="text/javascript">
    window.addEvent('domready', function(){
    $$('a[href="http://mywebsite.com"]').setStyle('color', '#7cc576');

    $$('a[href!="http://mywebsite.com"]').setStyle('color',
    '#9e0b0f');

    $$('a[href^=mailto:]').setStyles({
    // Remove link underline first
    'text-decoration' : 'none',
    // Add a dashed bottom border
    'border-bottom' : '1px dashed #9e0b0f',
    // Set background color
    'background-color' : '#7da7d9'
    });

    $$('a[href$=.zip]').setStyles({
    // Remove link underline first
    'text-decoration' : 'none',
    // Assign a different font style
    'font' : 'bold 14px "Courier New"',
    // Give them some padding
    'padding' : 2,
    //Add a solid gray border around the link
    'border' : '1px solid #898989',
    });

    });
    </script>

What just happened?

We experienced how attribute selectors can help us write complex DOM selections. More specifically, we:

  • Used the = attribute selector to select all links that point to http://mywebsite.com and assigned them a green color
  • Used the ! = attribute selector to select all links that don't point to http://mywebsite.com and gave them a red color
  • Used the ^ = attribute selector to select all links that have an href attribute value that begins with mailto: to give users a visual clue that when the link is clicked, it will open up their default mail client; we gave these links a dashed underline and light blue background.
  • Used the $= attribute selector to select all links that have an href attribute value the end in .zip to distinguish links that point to ZIP files; we gave these links a different font style and a gray border.

Attribute selector case sensitivity

When using attribute selectors, the criteria values you give them are case-sensitive. For example, in the example that uses http://mywebsite.com as the criteria for the = attribute selector, writing:

$$('a[href!="http://MyWebsite.Com"]').setStyle('color', '#9e0b0f');

This will not work! It's important to make sure you have the exact cases for the values you're trying to match. You'll have to extend your selector if you want to match different strings.

A common problem is in file extensions. Many people will write .ZIP as well as .zip, so your selector should look like this:

$$('a[href$=.zip], a[href$=.ZIP"]').setStyles({
...
});

Note that we just added another selector string that matches all links with an href attribute value that ends in .ZIP.

DOM selection makes unobtrusive JavaScript do-able

Throughout this article, we've just seen how to create very narrow and refined DOM element selections. This will enable us to pinpoint exactly the elements we need to operate on.

What this means is that we're able to write JavaScript without touching our HTML markup. We simply have to hone into the elements we want to work on using the selection techniques we learned in this article.

Summary

In this article we learned about:

  • The $() and $$() functions: how to use them to select DOM elements
  • Pseudo-class selectors: how to use them to select otherwise difficult sets of DOM elements such as "all even rows of a table"
  • Attribute selectors: how to further refine our selections by matching attribute (otherwise known as properties) values of elements in the DOM

We also discussed how the $$() function uses a similar syntax to CSS selectors, common mistakes to avoid in using the dollar and dollars functions, as well as the case sensitivity of attribute selector criteria.

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

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
K
c
E
G
s
i
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