Collections
The jQuery() function returns a jQuery object that can be treated as a collection of matched elements in the DOM based on passed argument(s). Argument can be:
- string with css selector
- an existing jQuery object
- DOM element or array of DOM elements
- an object of type PlainObject
- string with HTML code, that will be parsed; further you can add it to document
The $() function is synonymous of jQuery() function.
// select all <li> elements in document and add them class bar
$("li").addClass("bar");
$("li").each(function( index ) {
console.log( index + ": " + $(this).text());
});
Below is a list of properties and methods that allow you to treat a jQuery object as a collection.
property | description |
---|---|
length | Contains the length of collection. |
method | description |
get(ind) | Retrieves the element in the collection by index. You can also use the [] operator. You can use a negative value, in which case the index is treated as length - ind. |
first() | Returns new jQuery object from the first element. |
last() | Returns new jQuery object from the last element. |
eq(ind) | Returns new jQuery object from the specified element. You can use a negative value, in which case the index is treated as length - ind. |
slice(start [, end]) | Returns new jQuery object from the specified range. If end is omitted, all elements after start will be included in the result. |
add(el) | Returns new jQuery object with elements added to the current selection.
|
each(cb) | Executes a cb callback for each element in the collection. The cb callback has two parameters
|
map(cb) | Creates a new jQuery object containing the return values of calling cb callback on each element. The cb callback has two parameters:
|
filter(sel | cb) | Creates a new jQuery object by filtering the collection using a given selector or callback function. The sel parameter can be
The cb callback must return a boolean value. It has two parameters:
|
index(obj) | Returns the position of the passed element or -1 if the element is not found. |
toArray() | Returns collections of the DOM elements as an Array. |
is(sel | cb) | Returns true if at least one element matches the given arguments. The sel parameter can be
The cb callback must return a boolean value. It has two parameters:
|