Home  > Resources  > Blog

The jQuery Object

 
October 25, 2010 by Bibhas Bhattacharya
Category: Ajax & Web 2.0

What does the jQuery core function – $() – actually return? So much emphasis is put on what this function takes as input, the return type is almost ignored.

The core function $() or jQuery() returns a jQuery object that is a collection of all DOM element objects that match the supplied selector rule. This jQuery object builds on top of the JavaScript Array API. For example, you can obtain the length:

$("p").length; //Number of paragraphs in the page.

To obtain a DOM element object in the collection, simply call get(index). The index is zero based. For example:

$("p").get(1).innerHTML; //Get the inner HTML of the second paragraph.

To call DOM API, you must get a DOM element from the collection. For example:

//Get all the p elements that are 
//children of the first div element.
$("div").get(0).getElementsByName("p");
//Following is an error. jQuery object is not a DOM element 
$("div").getElementsByName("p"); //Error!

While the jQuery object does not support DOM methods, it supports more methods than the JavaScript Array. These methods, like text() and css() form the heart of jQuery’s magic. Some of these methods have dual read and write use. For example, text(string) sets the inner text value of elements. While, text() returns the inner text. When you invoke a write method for the jQuery object, jQuery internally applies it to all DOM elements in the collection:

$("p").text("Hello!"); //Change text of all paragraphs to Hello!.

A getter function normally works on the first DOM element in the collection only.

$("p").text(); //Returns the text of the first paragraph only.

Converting Objects

We have already seen that to get a DOM object from a jQuery object, you call the get(index) method. But, how do we get a jQuery object for a DOM object? To convert a DOM element object into a jQuery collection do:

$(elementObject)

For example:

var e = document.getElementById("p1"); //Get the DOM element
var jObj = $(e); //Convert DOM element to jQuery object
jObj.hide(); //Call jQuery API

Which Object for Event Handlers?

The jQuery event handler registration functions like click() and hover() are just simple wrappers of the DOM event handler registration functions. In other words, these functions behave the same way as if you attached them using DOM’s addEventListener (or attachEvent for older IE). That means, the "this" keyword within the function points to the DOM element for which the function is being called. For example:

$("#myDiv").click(function() {
    this.innerHTML = "Clicked!"; //Straight DOM API
    $(this).css("background", "yellow"); //jQuery API
});

Follow Us

Blog Categories