On the previous article, I introduced jQuery and showed how to enable it in your web app, along with a little insight on the basics. Now I’ll start showing some of the most useful methods you will find in the library, along with a sample for each. jQuery API is normally split into the following categories:
- jQuery Core – Core of the library: jQuery function, object assessors, extensibility and interop methods.
- Selectors – Filtering and selection operators and attributes to use in jQuery function – #().
- Attributes – Generic attribute manipulation methods, including class, text, html and value attributes.
- Traversing – DOM traversing and selection filtering mechanisms.
- Manipulation – Element manipulation methods, like text, html and boundary content.
- CSS – CSS manipulation within elements.
- Events – Eventing portion of the API. Handles typical object UI events. Very useful.
- Effects – Some nice effects are made available out of the box like fades.
- Ajax – Ajax requests and events.
- Utilities – General auxiliary methods for browser and feature information and array manipulation.
- Internals – Other core methods that you probably won’t need.
In my opinion, each one of these categories is important and has something you might want to use in your web site development routine. Element selection, value manipulation, DOM traversing, visibility handling, eventing, styles and appearance, async calls, etc. You’ll want this jQuery behavior in your code from the moment you end up reading this set of articles. So, the best thing for me to do in order to make you productive with this is to explain and show an example of the most useful features and common usage examples of the jQuery API.
For starters, let’s see how we can manipulate style attributes in DOM objects using jQuery. You often need to change element style attribute values dynamically whether it’s for animation purposes, highlighting, or UI perception logic. The normal javascriptian way of doing it is like this:
document.getElementById("MyDOMobject").style.display = "none";
This line of code would make the element in question invisible. The same could be done in jQuery the following way:
$("#MyDOMobject").css("display", "none");
So after “grabbing” my element named “MyDOMobject” with the jQuery marker $, I’ve used the css(name, value) method. What this does is change a given style attribute name to the specified value. On the other hand, in order to read a given style attribute value, the css(name) signature should be used.
Similarly, the attr() method allows you to read/change a given element attribute. For instance, the following line of code…
$("div:first").attr("id");
… would search for the first div in the document, and return the value of the “id” attribute. Pay no attention to the selection part, we will discuss that later (I’m just throwing some bones here and there to spice things up!).
To change the value of an attribute, we do this:
$("input[type=checkbox]").attr("disabled", "true");
This last bit of code selects all document checkboxes and disables them by setting the “disabled” attribute to true. Similarly, we have methods to change element text, html and values. You have the text(), html() and val(), just like the css() method. For instance, you can set the html code within a div element with html() like this:
$("div:last").html("jQuery example from .net Brainwork!");
Output: “jQuery example from .net Brainwork!”.
The text() method has the same purpose, except that it escapes all html:
$("div:last").text("Another jQuery example from .net Brainwork!");
Output: “Another jQuery example from .net Brainwork!”
The val() method gets or sets the value attribute in the appropriate elements like in this example, where all text fields values are changed:
$("input[type=text]").val("jQuery val() demo from .net Brainwork!");
The same method with no parameters returns the value of all affected elements.
This subset of jQuery methods will allow you to perform come of the most common tasks when manipulating DOM elements with javascript. But one of the most powerful and interesting features in this API is the selection and filtering mechanism.
Like I’ve been demoing previously, you can write jQuery selection queries over the DOM using various criteria like the type of element, its relative position in the element tree, attribute values, etc. For instance, in the previous example I created a jQuery object by specifying “input”, which queries all input fields in the document as a result. I could also do:
// Select all document divs
$("div")
// Select all spans
$("span")
// Select all paragraphs
$("p")
I then added an extra condition, a squared bracket filter to select only the text input fields. The square brackets allow you to input specific conditions based on the element’s attributes:
// Select using a value criteria
$("input[value='brainwork example']")
// select all text fields with values greater than 10
$("input[type=text][value^=10]")
Now I’ll talk about some filters jQuery has to offer. These filters allow you to apply relative positioning, type and DOM depth constraints to your element selection criteria. I’ll start by talking about hierarchy filters. These are targeted to element positioning, and they’re nothing but a simple operator between elements that adds some significance between them. For instance, the following example selects all input fields that are next to a label, though the “+” operator:
$("label + input[type=text]").val("Another Brainwork example!");
“label” and “input” are the objects and “+” is the filtering operator. According to the previous example, the following input would be selected…
On the other hand, this wouldn’t…
Besides the “+” operator, which selects the next adjacent elements, there’s the “~” operator, that matches all sibling elements after the first specified element. For instance, consider the following scenario:
The following example selects all input fields after input field named #testfield, that have values greater than 5:
$("#testfield ~ input[type=text][value=5]").css("color", "#334455");
You also have the “>” operator to select child elements, and you can also include no operator if you wish to select all descendants:
// select all child div elements inside the #menu element and change their border to red
$("#menu > div").css("border-color", "red");
// Select all input fields inside the form and change their text color
$("form input").css("color", "black");
Neat
That does it for hierarchy, now onto positioning! jQuery uses the “:” operator to define some sort of filtering criteria over affected elements. Some of the most basic ones are:
$("p:last").css("color", "green"); // last paragraph on the document gets green text
$("tr:even").css("background-color", "red"); // even rows gets red background color
$("td:gt(2)").css("background-color", "blue"); // TD with index higher than 2 gets blue back color
$(":header").css("color", "black"); // matches all header elements and changes their text color to black
Then there are specific filters that select input fields of some type, like these examples:
// Selects all input, textarea, select and button elements, and hides them
$(":input").hide()
// changes all text input field's color to red.
$(":text").css("color", "red")
// clears all password fields
$(":password").val("")
// clears all file input fields that are children of #divupload element
$("#divupload > input:file").val("")
Don’t forget to check out the full API reference for other filters. In the next article I’ll talk about CSS a bit more and also the eventing features of the API.
Technorati Tags: jQuery, Javascript












