In jQuery you can select elements in a page using many various properties of the element, including:
If you know CSS selectors you will notice selectors in jQuery are the same (with minor exceptions).
Take the following HTML for example:
<a href="index.html"></a> <!-- 1 --> <a id="second-link"></a> <!-- 2 --> <a class="example"></a> <!-- 3 --> <a class="example" href="about.html"></a> <!-- 4 --> <span class="example"></span> <!-- 5 -->
Selecting by Type:
The following jQuery selector will select all
<a> elements, including 1, 2, 3 and 4.
Selecting by Class
The following jQuery selector will select all elements of class
example (including non-a elements), which are 3, 4 and 5.
Selecting by ID
The following jQuery selector will select the element with the given ID, which is 2.
Selecting by Possession of Attribute
The following jQuery selector will select all elements with a defined
href attribute, including 1 and 4.
Selecting by Attribute Value
The following jQuery selector will select all elements where the
href attribute exists with a value of
index.html, which is just 1.
Selecting by Indexed Position (Indexed Selector)
The following jQuery selector will select only 1, the second
<a> ie. the
second-link because index supplied is
eq(1) (Note that the index starts at
0 hence the second got selected here!).
Selecting with Indexed Exclusion
To exclude an element by using its index
The following selects
<a> elements, except that with the class
example, which is 1
Selecting with Exclusion
To exclude an element from a selection, use
The following selects
<a> elements, except those with the class
example, which are 1 and 2.
Selecting by Pseudo-state
You can also select in jQuery using pseudo-states, including
The following jQuery selector will only select the first
<a> element: number 1.
Combining jQuery selectors
You can also increase your specificity by combining multiple jQuery selectors; you can combine any number of them or combine all of them. You can also select multiple classes, attributes and states at the same time.
This would select an
<a> element that:
class1, class2, and class3
You can also separate different selectors with a comma:
$("a, .class1, #someID")
This would select:
Child and Sibling selection
jQuery selectors generally conform to the same conventions as CSS, which allows you to select children and siblings in the same way.
There might be cases when we want to select all elements but there is not a common property to select upon (class, attribute etc). In that case we can use the
* selector that simply selects all the elements:
$('#wrapper *') // Select all elements inside #wrapper element