官术网_书友最值得收藏!

  • MooTools 1.3 Cookbook
  • Jay Larry G. Johnston
  • 316字
  • 2021-04-02 19:07:09

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.

主站蜘蛛池模板: 阳原县| 石屏县| 通化县| 绵竹市| 峨眉山市| 三台县| 介休市| 泸水县| 信阳市| 怀仁县| 梁平县| 章丘市| 泽库县| 乐安县| 九龙城区| 巴南区| 安平县| 佳木斯市| 商南县| 阿鲁科尔沁旗| 镇江市| 宁陵县| 丹凤县| 富平县| 仁布县| 民丰县| 襄汾县| 维西| 丽江市| 孟村| 迭部县| 昌平区| 永济市| 南江县| 彭山县| 滁州市| 杭锦后旗| 克东县| 晋中市| 江华| 商丘市|