jQuery - YUI - AlloyUI Rosetta Stone

alloyui.com/rosetta-stone

Getting Started

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://somedomain.com/path/to/plugin.js"></script>
<script src="https://somedomain.com/path/to/anotherplugin.js"></script>

<script>
  $(document).ready(
    function() {
      // Do stuff with the $ object here
      $.foo.bar()
    }
  );
</script>

Loading Method: Statically loaded (by default).

Scope: The jQuery/$ objects are global.

Plugins: To go beyond base library functionality, jQuery has the concept of "plugins" which are loaded in via additional <script> tags, or a dynamic loader. All examples on this page use core library methods (no plugins).

<script src="http://yui.yahooapis.com/3.8.0/build/yui/yui-min.js"></script>

<script>
  YUI().use(
    'module1', 'module2', 'module3',
    function (Y) {
      // Do stuff with the Y object here
      Y.foo.bar()
    }
  );
</script>

Loading Method: Dynamically loaded (by default).

Scope: The YUI loader object is global, and the Y object is local to each "sandbox" (your callback function). However, the return value of YUI().use() is a Y object, which you can assign to a global variable [e.g. var Y = YUI().use(…);].

Modules: Functionality in the YUI library is provided by "modules", which are split between core (officially supported) and gallery (user contributed). Simply adding YUI().use(function(Y){}); doesn't get you much, so you will need to specify which modules you wish to use and the loader will fetch them for you. The following core modules should provide you all the functionality for the examples in this document:

YUI().use(
  'node', 'io', 'event', 'animation',
  function (Y) {
    // example code here
  }
);

If any additional modules are needed, they'll be specified in the "notes" section to the example.

<script src="https://cdn.alloyui.com/3.0.0/aui/aui-min.js"></script>
<link href="https://cdn.alloyui.com/3.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>


<script>
  // Same as YUI...
</script>

Common Idioms

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$('div.foo:first');
Y.one('div.foo');

Return the first element which matches the selector; in this case, the first div element with a class of foo.

jQuery and YUI use similar selector syntax, but jQuery has added extensions, mainly convenience pseudo-classes, to the Sizzle CSS3-compliant selector engine. :first is a jQuery extension.

YUI comes with three different selector engines; see the section on selectors.

YUI and AUI use the same selector engine.

var foo = $('div.foo:first');

foo.some_method();
var foo = Y.one('div.foo');

if (foo) {
  foo.some_method();
}

jQuery selector methods always return a list object with 0 or more elements.

Y.one() returns null if no elements match, so check if the node exists.

$('div.foo');
Y.all('div.foo');

Select all div elements with a class of foo.

var foo = $('div.foo');

if (foo.length) {
  ...
}
var foo = Y.all('div.foo');

if (foo.size()) {
  ...
}

If no elements match the selector, jQuery will return an empty list [] that is loaded with special jQ methods, while Y.all() returns an empty NodeList object.

Both are truthy even if they contain no elements, so use [].length and NodeList.size() to check for emptiness.

.find('p.foo:first');
.find('p.foo');
.one('p.foo');
.all('p.foo');

Finds p elements with class foo that are children of the given node.

$('<div/>');
Y.Node.create('<div/>');

Create a new <div/> element to the DOM. Element is not added to the document tree.

.html('foo');
.text('foo');
.val('foo');

.html();
.text();
.val();
.setHTML('foo');
.set('text', 'foo');
.set('value', 'foo');

.getHTML();
.set();
.set();
// In addition to YUI...

.html('foo');
.text('foo');
.val('foo');

.html();
.text();
.val();

.setHTML(html) is a convenience wrapper around .set('innerHTML', html).

.set() is a generic method in YUI for modifying element object properties. Use .setAttribute() to modify element attributes.

.val(inputValue) is a generic method of AUI for setting the value attribute of a node.

AUI overrides YUI's setHTML method to set the node's innerHTML content and overrides YUI's getHTML to return the node's innerHTML content.

jQuery and AUI overload getters and setters in the same methods. If a value is passed, these work as setters.

.attr('foo');
.attr('foo', 'bar');
.getAttribute('foo');
.setAttribute('foo', 'bar');
// In addition to YUI...

.attr('foo');
.attr('foo', 'bar');

.attr('foo') gets the value of the foo attribute.

.attr('foo', 'bar') sets the value of the foo attribute to bar.

Generic HTML attribute getters and setters. If only the name is passed, it works as a getter.

$.trim('foo');
Y.Lang.trim('foo');

Strips leading and trailing whitespace.

parent.append('<div/>');

Create a new div element and makes it a child of parent.

child.appendTo(parent);

Append child to parent, and return child.

.appendTo() was added in YUI 3.3.0.

parent = $('<div/>');

$('<p>foo<p>')
  .click(fn)
  .appendTo(parent);
parent = Y.Node.create('<div/>');

Y.Node.create('<p>foo</p>')
  .appendTo(parent)
  .on('click', fn);

Creates a new div element, then appends a p element with a click event subscription.

Note that YUI's on() method is not chainable, so it returns an event handle, not the p node.

// Remove #foo from its parent and
// detaches events and jQuery data.
$('#foo').remove();

// Removes #foo from #container.
$('#container').remove('#foo');
// Removes #foo from its parent, but doesn't
// detach events or YUI plugins.
Y.one('#foo').remove();

// Removes #foo and detaches events and plugins.
Y.one('#foo').remove(true);

// Removes #foo from #container.
Y.one('#container').removeChild(Y.one('#foo'));

jQuery's .remove() removes the node, purges its attached events, and deletes its associated jQuery data.

YUI's equivalent is .remove(true).

.empty();

Remove and destroy all of the nodes within the given node and also unregisters any events associated with the elements being destroyed.

.empty() was added in YUI 3.3.0.

.siblings();
.siblings(selector);
.siblings();
.siblings(selector);
.siblings(fn);

In addition to an optional selector string, YUI also supports passing a function to filter the returned siblings.

.next();
.next(selector);
.next();
.next(selector);
.next(fn);

Same considerations as .siblings().

.prev();
.prev(selector);
.previous();
.previous(selector);
.previous(fn);

Same considerations as .siblings().

.parent();
.get('parentNode');

Return the parent node of the given node.

.children();
.get('children');

Return all the element children of the given node.

.closest(selector);
.ancestor(selector);
.ancestor(fn);

Return the first ancestor that matches the given selector.

YUI supports using a fn instead of a selector to find an ancestor.

$.contains(node, descendant);
.contains(descendant);

Check if a node contains a certain descendant.

.show();
.hide();

Make DOM nodes appear/disappear.

.fadeIn();
.fadeOut();
.show(true);
.hide(true);

YUI's .show() and .hide() can be customized to use transitions supported by the transition module. These methods were added in YUI 3.3.0.

$.parseJSON('{"name":"Douglas"}');
Y.JSON.parse('{"name":"Douglas"}');

Convert a JSON string into an object.

YUI requires the json-parse module.

No jQuery equivalent.

Y.JSON.stringify({name: "Douglas"});

Convert an object into a JSON string. Requires YUI's json-stringify module.

$.proxy(fn, context);
Y.bind(fn, context);

Create a new function that will call the supplied function in a particular context.

.data(key);
.data(key, value);
.getData(key);
.setData(key, value);

Store data associated with a DOM element without modifying the DOM.

.removeData();
.removeData(key);
.clearData();
.clearData(key);

Remove the associated data.

Events

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$('#foo').click(fn);
$('#foo').focus(fn);
$('#foo').blur(fn);
$('#foo').mouseout(fn).mouseover(fn);

// jQuery 1.4.2 and later allows you to
// register events when creating the element
$('<p/>',
  {
    blur: fn,
    className: 'bar',
    click: fn,
    focus: fn,
    text: 'foo'
  }
);

//Alternatively, you can use the bind() method
$('#foo').bind('click', fn);
Y.one('#foo').on('click', fn);
Y.one('#foo').on('focus', fn);
Y.one('#foo').on('blur', fn);
Y.one('#foo').on('mouseout', fn);
Y.one('#foo').on('mouseover', fn);

// Alternatively, YUI allows you to attach multiple
// subscribers with a single call.
Y.one('#foo').on(
  {
    blur: fn,
    click: fn,
    focus: fn,
    mouseout: fn,
    mouseover: fn
  }
);

// Or attach a single subscriber to multiple events.
Y.one('#foo').on(['blur', 'click', 'focus'], fn);

YUI's .on() is not chainable by default, but multiple subscribers can be attached in one call using the syntax shown.

$('#container').delegate('#target', 'click', fn);
Y.one('#container').delegate('click', fn, '#target');

Event listener will bind to #container and only fire the callback fn when a event's target is #target.

$(document).on('click', '#target', fn);
Y.one(Y.config.doc).delegate('click', fn, '#target');

jQuery's delegate() is generally preferred over on() because of performance as well as chaining limitations (source).

.live() was deprecated in jQuery 1.7, and removed in jQuery 1.9 in favor of .on().

$('#foo').trigger('click');
Y.one('#foo').simulate('click');

Simulate a click event.

Requires YUI's node-event-simulate module.

Selectors

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$('*');
Y.all('*');

Select all nodes.

Note the default selector engine for YUI is CSS 2.1.

Examples in this section require YUI's selector-css3 module.

$(':animated');

No YUI equivalent.

No AUI equivalent.

Psuedo class to select all elements currently being animated.

$(':button');
Y.all('input[type=button], button');
// In addition to YUI...

Y.all(':button');

Extension.

In both jQuery and YUI you can run multiple selectors separated by commas.

$(':checkbox');
Y.all('input[type=checkbox]');
// In addition to YUI...

Y.all(':checkbox');

Extension.

$(':checked');
Y.all(':checked');

CSS3 selector.

$('parent > child');
Y.all('parent > child');

Immediate child selector (child must be one level below parent).

$('parent child');
Y.all('parent child');

Descendant selector (child can be at any level below parent).

$('div.class');
Y.all('div.class');

CSS class selector.

$(":contains('foo')");
Y.all(':contains(foo)');

Extension to select all elements whose text matches 'foo'.

jQuery can take quotes or not.

YUI requires no quotes.

The text matching is plain string comparison, not glob or regexp. Be careful with this one as it will return all matching ancestors, eg [html, body, div].

$(':disabled');
$(':enabled');
Y.all(':disabled');
Y.all(':enabled');

CSS3 selector

'input[disabled]' and 'input:not([disabled])' work in both jQuery and YUI.

$(':empty');
Y.all(':empty');

CSS3 selector.

Selects all elements that have no child nodes (excluding text nodes).

$(':parent');
Y.all(':not(:empty)');
// In addition to YUI...

Y.all(':parent');

Inverse of :empty. Finds all elements that are a parent of at least one element.

jQuery's version is an extension.

YUI's version is using a CSS3 selector.

$('div:eq(n)');
Y.all('div').item(n);

Extension. Select nth element.

jQuery's selector will return an empty list [] on a match failure.

YUI's item() will return null if there is no nth element.

$('div:even');
$('div:odd');
Y.all('div').even();
Y.all('div').odd();

Extension. Select all even or odd elements. Note that elements are 0-indexed and the 0th element is considered even.

See YUI's NodeList.modulus(n, offset).

$(':file');
Y.all('input[type=file]');
// In addition to YUI...

Y.all(':file');

Extension. Find input elements whose type=file.

$('div:first-child');
Y.all('div:first-child');

CSS3 selector. Select the first child element of divs.

$('div:first);
Y.one('div');

The .one() method returns null if there is no match, and a single Node object if there is.

$('div:gt(n)');
$('div:lt(n)');

// Or
$('div').slice(n + 1);
$('div').slice(0,n);
Y.all('div').slice(n + 1);
Y.all('div').slice(0, n);

Extension. :gt (greater than) selects all elements from index n + 1 onwards. :lt (less than) selects all nodes from 0 up to n-1.

$('div:has(p)');
var nodes = [];

Y.all('div').each(
  function (node) {
    if (node.one('p')) {
      nodes.push(node);
    }
  }
);

nodes = Y.all(nodes);

Extension. Select elements which contain at least one element that matches the specified selector.

Select all div tags which have a p tag descendant.

$(':header');
Y.all('h1,h2,h3,h4,h5,h6');
// In addition to YUI...

Y.all(':header');

Extension. Select all heading elements. (Rarely used)

$('div:hidden');
var hidden = [];

Y.all('div').each(
  function(node) {
    if ((node.get('offsetWidth') === 0 &&
        node.get('offsetHeight') === 0) ||
        node.get('display') === 'none') {
        hidden.push(node);
    }
  }
);

hidden = Y.all(hidden);
// In addition to YUI...

Y.all(':hidden');

Extension.

In jQuery > 1.3.2 :hidden selects all elements (or descendants of elements) which take up no visual space. Elements with display:none or whose offsetWidth/offsetHeight equal 0 are considered hidden. Elements with visibility:hidden are not considered hidden.

YUI's equivalent would essentially be a port of the jQuery code that implements :hidden. This might be a good candidate for a patch to YUI.

$('#id');
Y.all('#id');

CSS3 selector. Identity selector.

$('input:image');
Y.all('input[type=image]');
// In addition to YUI...

Y.all(':image');

Extension. Select all inputs of type image.

$(':input');
Y.all('button,input,select,textarea');
// In addition to YUI...

Y.all(':input');

Extension. Select all user-editable form elements.

$(':last-child');
Y.all(':last-child');

CSS3 selector.

$('div:last');
var last,
    len  = list.size(),
    list = Y.all('div');

if (len) {
  last = list.item(len - 1);
}

Extension. Select the last element matched by the selector.

$('input[type=checkbox][checked]');
Y.all('input[type=checkbox][checked]');
// In addition to YUI...

Y.all(':checkbox:checked');

CSS3 selector. Multiple attribute selector.

$(':not(div)');
Y.all(':not(div)');

CSS3. Negation selector.

$(':password');
Y.all('input[type=password]');
// In addition to YUI...

Y.all(':password');

Extension.

$(':radio');
Y.all('input[type=radio]');
// In addition to YUI...

Y.all(':radio');

Extension.

$(':reset');
Y.all('input[type=reset]');
// In addition to YUI...

Y.all(':reset');

Extension.

$(':selected');
Y.all('option[selected]');
// In addition to YUI...

Y.all(':selected');

Extension.

$(':submit');
Y.all('input[type=submit]');
// In addition to YUI...

Y.all(':submit');

Extension.

$(':text');
Y.all('input[type=text]');
// In addition to YUI...

Y.all(':text');

Extension. (Does not select textarea elements)

Effects

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$('#foo').animate(
  {
    height:  100,
    opacity: 0.5,
    width: 100
  },
  {
    duration: 600,
    easing: 'swing'
  }
);
var a = new Y.Anim(
  {
    duration: 0.6,
    easing: Y.Easing.bounceOut,
    node: '#foo',
    to: {
        height:  100,
        opacity: 0.5,
        width:   100
    }
  }
);

a.run();

// Or use transition

Y.one('#foo').transition(
  {
    duration: 0.6,
    easing: 'ease-out',
    height:  100,
    opacity: 0.5,
    width:   100
  }
);

The basic syntax and capabilities of both animation libraries are very similar.

jQuery has convenience methods for effects like .fadeIn(), .slideUp(), etc. jQuery core has two easing functions: 'linear' and 'swing', but jQuery UI comes with many more effects as plugins.

YUI has several easing algorithms built-in, and offers additional tools such as animations over Bezier curves. Requires YUI's anim module.

Use YUI's transition module for simple transitions.

$('#foo').fadeOut();

// Or

$('#foo').hide(600);
Y.one('#foo').hide(true);

jQuery's .fadeOut() fades the opacity to 0, then sets display: none on the element. .fadeIn() is naturally the inverse.

YUI equivalents are .hide(true) and .show(true). (YUI's transition module must be loaded in order to get the fade effects)

jQuery effects tend to default to 200 or 600ms while YUI's show/hide transitions default to 500ms. jQuery durations are set in milliseconds; YUI durations are in fractions of seconds.

Array vs. NodeList

The fundamental unit of jQuery is a JavaScript Array containing 0 or more DOM elements. These Array objects have extra .on(), .click(), .map(), etc methods attached to them in addition to the built-in list operations like .slice() and .concat().

The fundamental units in YUI are Node objects, which wrap DOM elements, and NodeLists which are collections of Nodes. NodeLists are not Arrays and are not natively iterable.

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$('.foo').array_method(args);
Y.all('.foo').array_method(args);

Any Array operation that you can perform on a jQuery list can be translated to YUI in this form.

YUI NodeList objects are not native Arrays, but do provide wrapper functions for the most common array methods as of YUI 3.3.0.

$('div').slice(x, y);
Y.all('div').slice(x, y);

Return the xth to the yth div elements.

$('div').add('p');
Y.all('div').concat(Y.all('p'));

Add nodes that match the specified selector.

$('.foo').each(
  function() {
    $(this).some_method();
  }
);
Y.all('.foo').each(
  function() {
    this.some_method();
  }
);

.each() is like the for loop.

YUI's each() returns the original NodeList to help with chaining.

$('.foo').filter('.bar');
Y.all('.foo').filter('.bar');

The .filter() method in both libraries both take CSS selectors as filter criteria.

jQuery's .filter() can also take a function.

$('.foo').filter(
  function (idx) {
    return this.property === 'value';
  }
);
Y.all('.foo').filter(
  function (node) {
    return node.get('property') === 'value';
  }
);

Classic functional programming filter function. Given a list of elements, run the function on each and return a list of those which evaluated true.

$('.foo').map(
  function(idx, el) {
    return some_function(el);
  }
);
var mapped = [];

Y.all('.foo').each(
  function (node) {
    mapped.push(some_function(node));
  }
);

mapped = Y.all(mapped);

jQuery's .map() returns a jQuery-wrapped array of the return values of calls to the given function.

Ajax

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$.ajax(
  {
    data: data,
    success: successFn,
    url: url
  }
);
Y.io(
  url,
  {
    data: data,
    on: {
      success: successFn
    }
  }
);

jQuery.ajax() has some interesting options for async, context, and filtering.

YUI.io has extra options for failure mode callbacks, headers, cross-frame i/o, etc. Requires YUI's io module.

No equivalent.

Y.io(
  url,
  {
    data: data,
    on: {
      success: successFn
    },
    xdr: {
      use: 'flash'
    }
  }
);

Cross-domain requests via a Flash helper.

$('#message').load('/ajax/test.html');
Y.one('#message').load('/ajax/test.html');
Y.one('#message').load('/ajax/test.html', '#foo');

Load the content of a given URL and replace the contents of #message with it.

YUI's node-load module provides this functionality. YUI also optionally supports extracting only a portion of the loaded content if a selector string is passed as the second argument (assuming the content is HTML).

$.getJSON(url, successFn);
Y.io(url,
  {
    on: {
      success: successFn
    }
  }
);

A remote request for a JSON file. Same-origin policy is enforced.

There is no convenience method for this in YUI.

$.getJSON(
  "/some/jsonpURL.json?callback=?",
  successFn
);
Y.jsonp(
  "/some/jsonpURL.json?callback={callback}",
  successFn
);

JSONP requests. Same-origin policy is not enforced. Requires YUI's jsonp module.

CSS

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
.addClass('foo');
.removeClass('foo');
.toggleClass('foo');
.hasClass('foo');

CSS class name manipulation.

.removeClass('foo').addClass('bar');
.replaceClass('foo', 'bar');

Replace node's CSS class foo with bar.

.css('display', 'block');
.setStyle('display', 'block');

Set a single CSS property.

.css(
  {
    display: 'block',
    height:  100,
    width:   100
  }
);
.setStyles(
  {
    display: 'block',
    height: 100,
    width:  100
  }
);

Set multiple CSS properties.

.css('display');
.getStyle('display');

Get the current value for a CSS property.

.height();
.width();
.getComputedStyle('height');
.getComputedStyle('width');
// In addition to YUI...

get('offsetWidth') - getPadding('lr') - getBorderWidth('lr')

Computed height / width. (Excludes padding and borders)

AUI getBorderWidth has values of t(top), l(left), r(right), b(bottom).

.innerHeight();
.innerWidth();
.get('clientHeight');
.get('clientWidth');
// In addition to YUI...

get('offsetWidth') - getBorderWidth('lr')

Includes padding but not border.

AUI getBorderWidth has values of t(top), l(left), r(right), b(bottom).

.outerHeight();
.outerWidth();
.get('offsetHeight');
.get('offsetWidth');

Includes padding and border.

.offset();
// {
//  height: 1011,
//  left: 123,
//  top: 456,
//  width: 789
// }
.getXY();
// [123, 456]

Get the computed x,y coordinates relative to the document.

jQuery also returns the size of the node.

.offset(
 {
  left: 123,
  top: 456
 }
);
.setXY(123, 456);
// In addition to YUI...

// Center an item on the page
.center();

Set the x,y coordinates relative to the document.

Language Utilities

jQuery 1.8.3 YUI 3.8.0 AUI 3.0.0 Notes
$.each([1, 2, 3], fn(index, value));
$.each({ key: value }, fn(key, value));
Y.Array.each([1, 2, 3], fn(value, index))
Y.Object.each({ key: value }, fn(value, key));

Iterate through an array or object.

In jQuery, the first parameter is the index of the value in the array.

YUI is compatible with the Array forEach method so the first parameter the callback receives when iterating through an array is the value.

$.inArray(value, array);
Y.Array.indexOf(array, value);

Returns the index of the searched value in the specified array.

$.type(obj);
Y.Lang.type(obj);

Returns a string representing the type of the specified object. YUI and jQuery results are compatible (see jQuery's).

$.isPlainObject(obj);
Y.Lang.isObject(obj);
Y.Lang.isObject(obj, true);

YUI's Y.Lang.isObject returns true for arrays and functions. Passing true as a second parameter makes it return false if the input is a function.

$.isArray(obj);
$.isFunction(obj);
Y.Lang.isArray(obj);
Y.Lang.isFunction(obj);
Y.Lang.isString(obj);
Y.Lang.isBoolean(obj);
Y.Lang.isDate(obj);
Y.Lang.isNumber(obj);
Y.Lang.isNull(obj);
Y.Lang.isUndefined(obj);
Y.Lang.isValue(obj);

YUI also has some extra type checking functions. In particular, Y.Lang.isValue() returns false if the object is null, undefined or NaN, and true in any other case.

$.isEmptyObject(obj);
Y.Object.isEmpty(obj);

Check if the given object does not have any properties.

$.makeArray(obj);
Y.Array(obj);

Make an array-like object, for instance the return value of document.getElementsByTagName, into a true array.

$.now();
Y.Lang.now();

Return the current time in milliseconds.

Credits

The jQuery - YUI 3 Rosetta Stone was originally created by Carlos Bueno. It's now maintained by Ryan Grove and Paul Irish.

The jQuery - YUI 3 - AlloyUI Rosetta Stone is a fork and is maintained by The AlloyUI Team.

alloyui.com/rosetta-stone

How to Contribute

For YUI, please file bugs and recommend changes on GitHub. You're also more than welcome to fork the GitHub repo and send pull requests.

For AUI, please send Pull Requests on GitHub.