MooTools 1.3 Cookbook
上QQ阅读APP看书,第一时间看更新

Removing a group of elements using CSS selectors

Have an offending group of HTML elements? This task will obliterate them in one fell swoop.

Getting ready

CSS Selectors are used in styling to grab specific elements. This makes them a great way to also identify and group elements of our HTML DOM. Remember, grab single elements by their ID attributes; those are always unique on a page.

How to do it...

Grab groups of elements by CSS selector, most frequently by class. In our example, we use both class and tag CSS syntax to group together elements that we will remove.

<script type="text/javascript" src="mootools-1.3.0.js"></script>
</head>
<body>
<p class="remove"><span>The </span>
Fox jumped over the lazy dog.</p>
<p class="remove">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 class="nomove">You will find the culprit <span>over </span>
there.</p>
<p class="nomove">We all know <span>the </span>
ways to write good code.</p>
<div>The rain fell mainly upon the green <span>trees</span>
of Spain.</div>
<br/>
<div>Sentences should end
<span>with a period, right?</span></div>
<br/>
<form action="javascript:" method="get">
<input id="my_trigger" type="button" value="Go!"/>
</form>
<style type="text/css">
p span, div span { color:#F00; }
p.remove { font-weight:bold; }
</style>
<script type="text/javascript">
// for effect, grab the elements before moving them
var my_elements_to_REmove = $$('p.remove span');
$('my_trigger').addEvent('click',function() {
// move the element group by tag
my_elements_to_REmove.destroy();
});
</script>

How it works...

The styles defined cause our paragraph elements with class remove to be bold. This helps us see what is happening. Our CSS selector is p.remove span, so all SPAN tags found within a paragraph tag with class remove are selected and grouped into the variable my_elements_to_REmove. We then use a click listener on my_trigger to fire the destroy method on this group of elements.

There's more...

Being familiar with CSS selectors is quite crucial in our work with MooTools. Always remember the rule-of-thumb:

  • Single elements: grab using $('my_id')
  • Multiple elements: grab using $$('#my .css_selector')

We can bone up on CSS selectors at W3Schools' excellent syntax and tutorial section http://www.w3schools.com/css/css_syntax.asp.