Providing Technology Training and Mentoring For Modern Technology Adoption
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.
$("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.
//Following is an error. jQuery object is not a DOM element
$("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.
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:
var e = document.getElementById("p1"); //Get the DOM element
var jObj = $(e); //Convert DOM element to jQuery object
jObj.hide(); //Call jQuery API
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:
this.innerHTML = "Clicked!"; //Straight DOM API
$(this).css("background", "yellow"); //jQuery API
Your email address will not be published. Required fields are marked *