YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Selector Utility: Using filter

# Selector Utility: Using filter

Clicking the button will alert the number of items with the class of "selected" applied.

View example in new window.

- lorem
- ipsum
- dolor
- sit

- lorem
- ipsum
- dolor
- sit

- lorem
- ipsum
- dolor
- sit

1. lorem
2. ipsum
3. dolor
4. sit

## Using filter

The filter method, part of the YUI Selector Utility, makes it easy to filter a set of nodes based on a CSS3 Selector.

To illustrate the use of filter, we'll create a few HTML lists. When the button is clicked, we filter the collection of `LI`elements, so that only those that have the class `selected` applied are left in the array.

Add some markup for the lists and a button to trigger the demo:

<ul> <li class="selected">lorem</li> <li>ipsum</li> <li>dolor</li> <li>sit</li> </ul> <ul> <li>lorem</li> <li class="selected">ipsum</li> <li>dolor</li> <li>sit</li> </ul> <ul> <li>lorem</li> <li>ipsum</li> <li>dolor</li> <li class="selected">sit</li> </ul> <ol> <li>lorem</li> <li>ipsum</li> <li>dolor</li> <li class="selected">sit</li> </ol> <button id="demo-run">run</button>

Now we will define the function that filters the nodes when the button is clicked, and assign it as a click handler.

<script type="text/javascript"> var nodes = document.getElementById('selector-demo').getElementsByTagName('li'); var handleClick = function(e) { nodes = YAHOO.util.Selector.filter(nodes, '.selected'); alert(nodes.length); }; YAHOO.util.Event.on('demo-run', 'click', handleClick); </script>

This is a basic example of how to use the `Selector.filter` method.

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

Note: Logging and debugging is currently turned off for this example.

Reload with logging
and debugging enabled.

### Selector Utility Examples:

- Using query
- Using filter
- Complex Application (included with examples for Layout Manager)

### More Selector Utility Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2010 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings