Moving a group of elements using their HTML tag

Feel the managerial power as we move a little army of elements to their new position in our HTML.

Getting ready

When working with a complex form, all methods of grabbing elements are useful. We may wish to loop over all select values or option elements. There could be business requirements for the form to validate each type of element a certain way.

How to do it...

Often the gaming industry propels code development more than the business community. Games require flexible code that can be written with a minimum of syntax. Here is a recipe that might give us some ideas on how a word game could be created.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<p><span>The </span> Fox jumped over the lazy dog.</p>
<p>Jack and Jill went up one
<span>hill </span> and down another.</p>
<p>By any other name, this
<span>rose </span> is still a rose.</p>
<p>The superhero towered
<span>high </span> above all others.</p>
<p>You will find the culprit
<span>over </span> there.</p>
<p>We all know
<span>the </span> ways to write good code.</p>
<p>The rain fell mainly upon the green
<span>trees</span> of Spain.</p>
<p>Sentences should end with a period,
<span>. </span> right?</p>
<form action="" method="get">
<input id="my_trigger" type="button" value="Go!"/>
</form>
<hr/>
<h1 id="my_new_sentence"></h1>
<script type="text/javascript">
// for effect, grab the elements before moving them
var my_elements_to_move = $$('span');
$('my_trigger').addEvent('click',function() {
// move the element group by tag
my_elements_to_move.inject('my_new_sentence');
});
</script>

How it works...

The double dollar object, $$() takes a Cascading Style Sheet (CSS) selector, which can be a tag, class, descendant operator, or anything the CSS specification allows.

With this type of simple markup where we do not even need classes or ID attributes, the code and resulting canvas text are easy to read and work with.

See also

Being sure we know where to find information on the actual CSS specifications is important, let us take a brief look at the World Wide Web Consortium, W3C's website: http://www.w3.org/Style/CSS/ or http://www.w3.org/TR/css3-selectors/#selectors.