These methods help us to work with the DOM elements underlying each jQuery object.
Returns the number of DOM elements matched by the jQuery object. .length |
Returns the number of DOM elements matched by the jQuery object. .size() |
Retrieves DOM elements matched by the jQuery object. .get([index]) |
The .get()
method grants us access to the DOM nodes underlying each jQuery object. Suppose we had a simple unordered list on the page:
<ul> <li>foo</li> <li>bar</li> </ul>
With an index specified, .get()
will retrieve a single element:
$().log('Get(0): ' + $('li’).get(0));
Since the index is zero-based, the first list item is returned:
Get(0): [object HTMLLIElement]
Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:
$().log('Get(0): ' + $('li’)[0]);
Without a parameter, .get() returns all of the matched DOM nodes in a regular array:
$().log('Get(): ' + $('li’).get());
In our example, this means that all list items are returned:
Get(): [object HTMLLIElement],[object HTMLLIElement]
Searches for a given DOM node from among the matched elements. .index(node) |
The complementary operation to .get()
, that accepts an index and returns a DOM node, .index()
takes a DOM node and returns an index. Suppose we had a simple unordered list on the page:
<ul> <li>foo</li> <li>bar</li> </ul>
If we retrieve one of the two list items, we can store it in a variable. Then .index()
can search for this list item within the set of matched elements:
var listItem = $('li’)[1]; $().log('Index: ' + $('li’).index(listItem));
We get back the zero-based position of the list item:
Index: 1