jQuery includes some expressions that aren't available in either CSS or XPath, but were found to be very handy, so were included.
The following expressions' syntax is based upon the various CSS selectors, of similar names.
Custom Selectors
- :even Selects every other (even) element from the matched element set.
- :odd Selects every other (odd) element from the matched element set.
- :eq(0) and :nth(0) Selects the Nth element from the matched element set
- :gt(4) Selects all matched elements whose index is greater than N.
- :lt(4) Selects all matched elements whose index is less than N.
- :first Equivalent to :eq(0)
- :last Selects the last matched element.
- :parent Selects all elements which have child elements (including text).
- :contains('test') Selects all elements which contain the specified text.
- :visible Selects all visible elements (this includes items that have a display of block or inline, a visibility of visible, and aren't form elements of type hidden)
- :hidden Selects all hidden elements (this includes items that have a display of none, or a visibility of hidden, or are form elements of type hidden)
Some examples:
$("p:first").css("fontWeight","bold");
$("div:hidden").show();
$("div:contains('test')").hide();
Form Selectors
There are a few selectors for form elements:
- :input Selects all form elements (input, select, textarea, button).
- :text Selects all text fields (type="text").
- :password Selects all password fields (type="password").
- :radio Selects all radio fields (type="radio").
- :checkbox Selects all checkbox fields (type="checkbox").
- :submit Selects all submit buttons (type="submit").
- :image Selects all form images (type="image").
- :reset Selects all reset buttons (type="reset").
- :button Selects all other buttons (type="button").
Also available is :hidden, see the description above for details.
It is recommended to provide a context when using the above:
$('#myForm :input')
Or, if you have already a reference to your form:
$('input:radio', myForm)
This would select all input elements of type radio inside myForm. Using :radio is mostly the same as [@type=radio], but should by slightly faster. Good to know when working with large forms.
jQuery