jQuery in Action

Managing the wrapped element set
35
direct reference to an element or elements to perform raw JavaScript operations
upon them.
Because jQuery allows us to treat the wrapped set as a JavaScript array, we can
use simple array indexing to obtain any element in the wrapped list by position.
For example, to obtain the first element in the set of all
<img>
elements with an
alt
attribute on the page, we can write
$('img[alt]')[0]
If we prefer to use a method rather than array indexing, jQuery defines the
get()
method for that purpose.
The fragment
$('img[alt]').get(0)
is equivalent to the previous example that used array indexing.
The
get()
method can also be used to obtain a plain JavaScript array of all the
wrapped elements. Consider:
var allLabeledButtons = $('label+button').get();
This statement wraps all the
<button>
elements on a page that are immediately
preceded by
<label>
elements in a jQuery wrapper and then creates a JavaScript
array of those elements to assign to the
allLabeledButtons
variable.
We can use an inverse operation to find the index of a particular element in
the wrapped set. Let's say for some reason we want to know the ordinal index of
an image with the
id
of
findMe
within the entire set of images in a page. We can
obtain this value with
var n = $('img').index($('img#findMe')[0]);
Command syntax: get
get(index)
Obtains one or all of the matched elements in the wrapped set. If no parameter is specified,
all elements in the wrapped set are returned in a JavaScript array. If an index parameter is
provided, the indexed element is returned.
Parameters
index
(Number) The index of the single element to return. If omitted, the entire set is
returned in an array.
Returns
A DOM element or an array of DOM elements.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.