My favorites | Sign in
Project Logo
                
Search
for
Updated Nov 30, 2008 by gregreimer
ReglibSelectors  
How reglib's selectors work

The API

reglib has a simple Selector API. Supposing you first executed this code:

var myElement = document.getElementById('baz');

The following demonstrates the entirety of what's possible with the Selector API.

var sel = new Selector('div#foo ul > li.bar');
if (sel.matches(myElement)) { ... }

This is just documented for posterity. You shouldn't ever need to use this API directly. reg functions and methods always accept plain selector strings and will convert them internally to Selector objects, often caching the compiled versions for future use.

Selector Syntax

If you're familiar with CSS, it should be fairly obvious what these selectors mean and how they work. However, for performance reasons, this is a stripped-down, souped-up implementation of CSS3 selectors, and the attribute selection syntax differs from CSS3:

/* CSS3 */
a[href=foo.html]
/* reglib */
a@href='foo.html'

Here's a rundown of the selection options:

Selector What it Selects
a a elements
a span span elements descended from a elements
a > span span elements that are direct children of a elements
a + span span elements that are immediate next siblings of a elements
a ~ span span elements that are following siblings of a elements
a, span any span or a element
a@title a elements having title attributes
a@title='foo' a elements whose title attributes equal foo
a@title^='foo' a elements whose title attributes begin with foo
a@title*='foo' a elements whose title attributes contain foo
a@title$='foo' a elements whose title attributes end with foo
a@title~='foo' a elements whose title attributes contain foo in a space-separated list.
a@title|='foo' a elements whose title attributes either exactly match foo or start with foo followed by a hyphen
a#foo a elements whose id equals foo
a.foo a elements whose class attributes equal foo, or contain foo in a space-separated list
a:target a elements whose id matches the URL hash
#foo or *#foo any element with an id that equals foo
.foo or *.foo any element with a class attribute that equals foo, or contains foo in a space-separated list
.foo.bar any element with a class attribute that contains both foo and bar in a space-separated list, order-agnostic
:target or *:target any element whose id matches the URL hash

Performance

If you're worried about performance, there are some considerations in choosing your selectors. Generally, less ambiguous selectors perform faster, more ambiguous selectors perform slower. For example:

The less ambiguity in the selector, the more search possibilities can be ruled out ahead of time, allowing the match to execute faster.


Sign in to add a comment
Hosted by Google Code