Skip to content

Instantly share code, notes, and snippets.

@lucaong
Created November 22, 2012 15:39
Show Gist options
  • Save lucaong/4131764 to your computer and use it in GitHub Desktop.
Save lucaong/4131764 to your computer and use it in GitHub Desktop.
Experiment with a nano-library for DOM selection

Usage:

the $query (aliased with $q) object exposes two methods: first() and all(). Both take a selector string as the first argument and, optionally, a context element as the second.

$q.first(".foo"); // => first element of class `foo`
$q.all(".foo");   // => array (yes, not NodeList) of all elements of class `foo`

var elem = $q.first("p");
$q.first(".foo", elem ); // => first child of `elem` of class `foo`
$q.all(".foo", elem );   // => all children of `elem` of class `foo`

Lazy evaluation of queries:

You can also build the query in advance and evaluate it lazily when you need:

var query = $q(".foo .bar"); // build the query

query.first() // => first element matching the selector, or null
query.all()   // => all elements matching the selector
(function( root ) {
function all( selector, ctx ) {
var list, ary = [];
ctx = ctx || document;
list = ctx.querySelectorAll( selector );
for ( var i = 0; i < list.length; i++ ) {
ary[ i ] = list[ i ];
}
return ary;
}
function first( selector, ctx ) {
ctx = ctx || document;
return ctx.querySelector( selector );
}
function $query( selector, ctx ) {
return {
all: function() {
return $query.all( selector, ctx );
},
first: function() {
return $query.first( selector, ctx );
}
}
}
$query.first = first;
$query.all = all;
root.$query = root.$q = $query;
})( this );
@asaaki
Copy link

asaaki commented Nov 22, 2012

Maybe you want to add this to http://microjs.com/#css :o)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment