Getting started
Ojay is quite similar to jQuery, in that it’s based on a programming model where you use CSS selectors to grab a collection
of elements from the page, then carry out actions on that collection. To grab a collection of elements, just use the Ojay
function:
var links = Ojay('a');
The Ojay function is aliased as $, so anywhere you see Ojay in the code examples here, you can use $ instead. You can
change the alias used as follows:
Ojay.changeAlias('_');
// Now you can grab elements with _('div.section')
Ojay.changeAlias returns the current alias to its original meaning, so you can use Ojay with Prototype et al and still use
Prototype’s $ function.
You can also pass an HTMLElement to Ojay so you can use Ojay’s API with it. You’ll see why this is useful later on.
var extendedBody = Ojay(document.body);
What’s a collection?
The Ojay function always returns an Array-like object containing zero or more elements that match your CSS query. The
collection is not strictly an Array, but it has a length property and you can access its elements by numeric indexes:
var link = Ojay('a')[0];
// link is an HTMLElement reference
The variable link in this example will be a raw HTMLElement object, without any of Ojay’s helpful extensions. If you want
an Ojay collection wrapping the element, use the at method:
var links = Ojay('a');
var betterLink = links.at(4);
So betterLink will be an Ojay collection with one element – the 5th element in the links collection.
Every collection has a special property called node, which refers to the first HTMLElement in the collection. Your
collections will frequently contain one element (e.g. if you refer to it by ID – Ojay('#container')) and node is a convenient
way to get at the raw element.
var h1 = Ojay('h1#title').node;
var tagName = h1.tagName.toLowerCase();
If you want a proper Array object, you can use the toArray method to return an Array of raw HTMLElement references.
var array = links.toArray();
The members of array will be regular HTMLElement objects with no Ojay helper methods.
