Java Reference
In-Depth Information
Digging Deeper Into jQuery
The code you wrote to test your jQuery installation gave you just a small taste of what the framework is
capable of. You saw how easy it was to change property values and add HTML to the page; well, pretty
much all operations are about as simple. Whether you're creating HTML elements and appending them
to the page or making Ajax calls to the server, jQuery lets you do it in an easy fashion.
jQuery is a DOM-centered framework, and to do any DOM manipulation you fi rst need to locate and
retrieve specifi c elements.
Selecting Elements
The W3C DOM standard gives you the getElementById() and getElementsByTagName() methods
to fi nd and retrieve elements in the DOM. These methods work perfectly fi ne, but their most obvious
drawback is they limit you on how you can select elements. You can either select elements by id attri-
bute value or by tag name. There may be times you want to select elements based on their CSS class
name or their relationship to other elements.
This is one area where jQuery truly shines; using CSS selectors, you can select elements based on their
CSS class name, their relationship with other elements, their id attribute value, or simply their tag
name. Let's start with something simple like this:
$(“a”)
This code selects all <a/> elements within the page and returns them in an array. Because it is an array,
you can use the length property to fi nd out how many elements were selected, like this:
alert($(“a”).length);
jQuery was designed to make DOM manipulation easy, and because of this design philosophy, you
can make changes to several elements at the same time. For example, you built a web page with over 100
links in the document, and one day you decide you want them to open in a new window by setting the
target attribute to _blank . That's a tall task to take on, but it is something you can easily achieve with
jQuery. Because you can retrieve all <a/> elements in the document by calling $(“a”) , you can call the
attr() method to set the target attribute. The following code does this:
$(“a”).attr(“target”, “_blank”);
Calling $(“a”) results in a jQuery object, but this object also doubles as an array. Any method you
call on this particular jQuery object will perform the same operation on all elements in the array. By
executing this line of code, you set the target attribute to _blank on every <a/> element in the page,
and you didn't even have to use a loop!
The next way you can select elements is with CSS id syntax; that is, the value of an element's id attribute
prepended with the pound sign ( # ). You could use the DOM's getElementById() method to perform
the same task, but using the jQuery function requires less keystrokes, and you have the benefi t of
returning a jQuery object.
$(“#myDiv”)
Search WWH ::




Custom Search