Analogizing jQuery & Dojo

This is an effort to create a comparision between jQuery and Dojo

Getting Started

jQuery 2.1 Dojo 1.7 Notes
Global Objects and functions jQuery or $ dojo

jQuery provides a function which can be accessed by jQuery or $ which can be used to access all the jQuery methods. Ideally it accepts CSS selectors, searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements.

Similarly dojo has a object which has all the methods.

Important

jQuery When we access an element with jquery say $(".bar") it returns a jquery object and not just the actual element, on which we can add methods through chaining to work upon.

eg. $("bar").addClass("foo").removeClass("foe"). And if we want to have only the DOM element, we have to do $("bar").get(0)

If there are more than one element which matches the criteria jQuery will return an array

Dojo However, DOJO will simply return the DOM element or an array in case we use dojo.query("bar"), and it matches quite a few elements.

DOM Ready
$(document).ready(
function(){
// Your code here
});
dojo.ready(
function () {
// Your code here
});
Fires when DOM is ready

jQuery Alternative Usage:

$(function(){
// Your code here
});

Common Idioms

jQuery 2.1 Dojo 1.7 Notes
Id Selector $("#bar") dojo.byId("bar") returns the element with id bar.
Class Selector $(".foo") dojo.query(".foo")

Selects all the elements with class foo.

$(".foo").length & dojo.query(".foo").length gives the length of the elements present for the given condition.

Element Selector $("td").find(".notes") dojo.query("td.notes") Gets all the td elements with class notes.
Pseudo class selectors $(".container:first-child") dojo.query(".container:first-child") Get the elements filtered through pseudo classes.
Creates a new DOM element $("<div/>") dojo.create("div") Usage:

jQuery

var e = $("<div/>").attr("id","last");
$("body").append(e);

Dojo

dojo.create("div",{"id":"last"},dojo.body());
                    
Get inner HTML of the element $("#bar").html() dojo.byId("bar").innerHTML Even setting the innerHTML is pretty much same

jQuery

$("#bar").html("Hola")

Dojo

dojo.byId("bar").innerHTML = "Hola"
Value of an element $("select:first").val() dojo.query("select")[0].value Set the value the same way

jQuery

$("select:first").val("Here is the first option")

Dojo

dojo.query("select")[0].value = "Here is the first option"
Attribute Values $(".active a").attr("href") //get

$(".active a").attr("href", "javascript:void(0);") //set
dojo.query(".active a").attr("href") //get

dojo.query(".active a").attr("href", "javascript:void(0);") //set
Get and set attribute values
Trim $.trim(" foo ") dojo.trim(" foo ") Trim strings. Examples will return foo
Create and append elements $("body").append('<\a href="/foo">Foo<\/a>') dojo.create("a", { href: "/foo", innerHTML: "Foo" }, dojo.body()); Creates an HTML element and appends to the given node
Remove an element $("#foo").remove() dojo.destroy("foo"); Remove the element as per the selector
Find all the child elements $(body).children(); dojo.query("body > *") Can use selectors to filter results eg.:

jQuery

$("body").children("div")

Dojo

dojo.query("body > div")

Events

jQuery 2.1 Dojo 1.7 Notes
Event Binding $("#foo"). bind("click", function(){ // do something }) dojo.connect(dojo.byId("foo"),"onclick",this,function(){ // do something }))

The third parameter in dojo.connect is the scope in which the following method should be executed.

Most of all the events can be bound this way.

Unbind Events $("#foo").unbind() var con = dojo.connect( dojo.byId("foo"),"onclick",this, function(){ // do something }));

dojo.disconnect(con);
In dojo you have to assign the dojo.connect to a variable and pass to dojo.disconnect to unbind the event.

Animations & Effects

jQuery 2.1 Dojo 1.7 Notes
Animate
$("#block").animate({
    width:   100,
    height:  100,
    opacity: 0.5
  }, 1500 );
  //$(domNode).animate({properties}, duration)
dojo.animateProperty({
  node:dojo.byId('block'),
  properties: {
    width:   100,
    height:  100,
    opacity: 0.5
  },duration : 1500
}).play();
Pretty much self explanatory
FadeIn $("#effects").fadeIn() dojo.fadeIn({ node:dojo.byId('effects') }).play();
FadeOut $("#effects").fadeOut() dojo.fadeOut({ node:dojo.byId('effects') }).play();

Selectors

jQuery 2.1 Dojo 1.7 Notes
Select All Nodes $("*") dojo.query("*")
CSS3 $(":button") dojo.query("input[type=button]")
CSS3 $(":checkbox") dojo.query("input[type=checkbox]")
CSS3 $(':checked') dojo.query("input:checked")
Descendent selector $('parent child') dojo.query(child, parent) Finds all the child of the parent element
Descendent selector $('parent > child') dojo.query(parent > child) Finds all the immediate children of the parent element
CSS3 $('input:disabled')
$('input:enabled')
dojo.query('input:disabled')
dojo.query('input:enabled')
Odd and Even $("body").find("div:nth-child(odd)");
$("body").find("div:nth-child(even)");
dojo.query("body div:nth-child(odd)");
dojo.query("body div:nth-child(even)");
Find all the odd and even divs
Negation selector $('.container:not(div)') dojo.query('.container:not(div)') Containing class container but not a div
Last Child $(".container:last-child") dojo.query(".container:last-child")
Extension $(':submit') dojo.query("input[type=submit]")
Extension $(':password') dojo.query('input[type=password]')
Extension $(':text') dojo.query('input[type=text]')

Array vs. NodeList

jQuery 2.1 Dojo 1.7 Notes
Looping through the jQuery or dojo nodelists
$("p").each(
function(){
$(this).addClass("foo");
});
dojo.query("p").forEach(
function(pa){
dojo.addClass(pa,'foo');
});

The nodelist thats being sent can be considered as an array, so you can perform operatiosn on it as you need.

jQuery

Can also do

$("p").addClass("foo")

IndexOf $.inArray("foo", arr) dojo.indexOf(arr, "foo");

Eg. Array var arr = ["foo", "bar", "zoo"];

Gives the indexOf the element if present else -1
Slice Nodelists $("a").slice(1, 3) dojo.query("a").slice(1, 3) Returns first two anchors on the query
Filter through NodeLists $("a").filter(".brand") dojo.query("a").filter(".brand") Filter the anchor with class brand
Filter with functions
$('a').filter(function () {
return $(this).attr("href") === '#';
});
dojo.query("a").
  filter(function(node){
    return dojo.query(node).attr("href") == '#';
  });
Can pass callbacks to filter
Map $.map($("a"), function(a, index){return $(a).parent().get(0)})
dojo.query("a").
map(function(node){
return node.parentNode;
});
Returns an array list by working on the array with the callback thats passed.

Ajax

jQuery 2.1 Dojo 1.7 Notes
Ajax Query
$.ajax({
  url:      url,
  type:     //GET(or)POST,
  data:     data,  
  success:  successFn
  error:  errFn,
  complete: completeFn
});
GET
dojo.xhrGet({
  url:      url,
  handleAs: typeofData //JSON, text
  content:     data,
  load:  successFn
  error:  errFn,
  handle: completeFn
});
POST
dojo.xhrPost({
  url:      url,
  handleAs: typeofData //JSON, text
  content:     data,
  load:  successFn
  error:  errFn,
  handle: completeFn
});
jQuery

Has a complete method can used along with success and error callbacks, called by the ajax method regardless of success or error

Dojo

Has a handle method can be used along with success and error callbacks, called by the ajax method regardless of load or error

Instead of content in POST calls we can use form through which we can pass in a form id and it will send the form values as key value pairs through the ajax call.

Load HTML $('#msg').load('/ajax/test.html');
dojo.xhrGet({
  url: "/ajax/test.html",
  load: function(newContent){
  dojo.byId("msg")
    .innerHTML = newContent;
  }
  ,error: function() {//don't do anything}
});
                  
Loads the content of a given URL in #message node.
JSONP
$.getJSON("http://search.twitter.com/
search.json?callback=?",{q: "vetri02"},
function(tweets) {
  // Handle response here
  console.info(tweets);
});
                  
dojo.require("dojo.io.script");

dojo.ready(function() {
  dojo.io.script.get({
  url: "http://search.twitter.com/search.json",
  callbackParamName: "callback",
  content:{q: "vetri02"},
  load: function(tweetsJson){
    console.info(tweetsJson);
  }
  });
});
                  
jQuery

jQuery uses the same getJSON for jsonp if you use callback parameter in the request

Dojo

Dojo uses dojo.io.script to make jsonp calls.

Notice we have added dojo.require("dojo.io.script");(used for making jsonp calls) this is how you add modules in dojo. Dojo has various modules for various purposes like say dojo.require("dojo.NodeList-traverse"); which provides features like .parents in jQuery. To use this you have to use all the dojo package.

Checkout David Walsh's post for more info

CSS

jQuery 2.1 Dojo 1.7 Notes
Class
$("#bar").addClass('foo')
$("#bar").removeClass('foo')
$("#bar").toggleClass('foo')
$("#bar").hasClass('foo')
                              
dojo.addClass("bar", "foo");
dojo.removeClass("bar", "foo");
dojo.toggleClass("bar", "foo");
dojo.hasClass("bar", "foo")
                              
hasClass on both gives a boolean value true or false based on the class if present on the element.
Removeclass $("#bar").removeClass('foo').addClass('bar') dojo.replaceClass("bar", "bar", "foo"); Dojo

In Dojo the first arguement is the node id, second is the class to be added and third to be removed.

Show and Hide
$("#bar").show()
$("#bar").hide()
dojo.style("bar", "display", "block");
dojo.style("bar", "display", "none");
                              
Set style
$("#bar").css({
  'height':  '100',
  'width':   '100',
  'display': 'block'
})
                              
dojo.style("bar", {
  'height':  '100',
  'width':   '100',
  'display': 'block'
});
                              
Position and size of an element $("#bar").offset() dojo.position("bar"); Returns values like
jQuery //{left: 123, top: 456, width: 789, height: 1011}
Dojo //{ w: 300: h: 150, x: 700, y: 900, }

More..

Utilities

jQuery 2.1 Dojo 1.7 Notes
forEach $.each([1, 2, 3], function(index, value){}) dojo.forEach([1, 2, 3], function(value, index){}) Iterate through array.
indexOf $.inArray(1, [1, 2, 3]) dojo.indexOf([1, 2, 3], 1); indexOf value in array