Yahoo! Developer Network Home - Help

YDN Site Search

# YUI Library Examples: Selector Utility: Using query

# Selector Utility: Using query

Clicking the button will add a red border to all of the LI elements with the class of "selected" that live in a UL.

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 query

The query method, part of the YUI Selector Utility, makes it easy to retrieve an array of elements based on a CSS3 Selector.

To illustrate the use of query, we'll create a few HTML lists. When the button is clicked, we will add a red border to all `LI`s that are descendants of `UL`s, and have the class `selected` applied.

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 adds the border when the button is clicked, and assign it as a click handler.

<script type="text/javascript"> var handleClick = function(e) { var nodes = YAHOO.util.Selector.query('ul li.selected'); YAHOO.util.Dom.setStyle(nodes, 'border', '1px solid red'); }; YAHOO.util.Event.on('demo-run', 'click', handleClick); </script>

This is a simple example of how to use the `Selector.query` method.

### 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 (beta))

### More Selector Utility Resources:

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

Copyright © 2008 Yahoo! Inc. All rights reserved.

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