Java Reference
In-Depth Information
This code assigns a special object, called a jQuery object, that represents an array of all <a/>
elements in the page to the elements variable.
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, imagine you built a web page
with more than 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, which gets or sets the value of an attribute, to set the
target attribute. The following code does this:
elements.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!
Because jQuery objects are an array, you can use the length property to find out how many
elements were selected with a CSS query:
var length = elements.length;
This information can be useful, but you usually won't need to know the length of a jQuery object.
The most common use of an array's length property is for looping, and jQuery is designed to work
with multiple elements at the same time. The methods you execute on a jQuery object have built‐in
loops; so, the length property is rarely used.
jQuery has a built‐in CSS selector engine, and you can use just about any valid CSS selector to
retrieve your desired elements—even if the browser doesn't support it. For example, IE6 does
not support the parent > child CSS selector. If you have the unfortunate need to support that
browser, jQuery can still select the appropriate elements with that selector. Consider the following
HTML as an example:
<p>
<div>Div 1</div>
<div>Div 2</div>
<span>Span 1</div>
</p>
<span>Span 2</span>
This HTML code defines a <p/> element that contains two <div/> elements and a <span/> element.
Outside the <p/> element is another <span/> element. Let's say that you need the <span/> element
inside the paragraph. You can easily select that element with the following:
var innerSpan = $("p > span");
This line of code uses the parent > child CSS selector syntax, and because jQuery has its own
CSS selector engine, this code will work in every browser.
Search WWH ::




Custom Search