As explained in Getting Started with jQuery, typically you use jQuery selectors to locate elements within the page to work on, then call jQuery methods to manipulate those elements.
jQuery selectors are based on CSS selectors, so if you’re familiar with CSS then you already understand the basic idea of selecting elements in the page.
In this tutorial you’ll look at pretty much all of the selectors supported by jQuery. Many of these are the same as CSS selectors, while some are specific to jQuery. For each selector you’ll see an example showing how to use the selector to find page elements.
You’ll look at the following topics:
- Basic selectors
- Selecting elements by attribute
- Selecting elements by content
- Selecting elements by hierarchy
- Selecting form fields
- Selecting elements by their position
- Other useful jQuery selectors
Here’s a list of all selectors supported by jQuery.
jQuery only supports CSS selectors that actually select DOM elements. For example, :visited
, :hover
and :first-line
aren’t supported.
Basic selectors
The basic selectors will be familiar to you if you’ve ever built a CSS layout or two. These are the selectors you’ll probably use 90% of the time when working with jQuery:
Selector | Description | Example |
---|---|---|
All | Selects all elements in the page, including head , body and so on. |
$("*") |
Element | Selects all elements with a given tag name. | $("p") $("div") |
Class | Selects all elements with a given CSS class. | $(".myClass") $("p.myClass") |
ID | Selects a single element with a given id attribute. |
$("#myID") $("p.#myID") |
You can also combine multiple selectors into a single selector using commas. jQuery then selects all elements that match any of the selectors. For example:
// Select all divs with a class of .myClass, as well as all paragraphs
var selectedElements = $("div.myClass, p");
Selecting elements by attribute
The basic selectors are great if, for example, you want to select all paragraphs in the page, or the element you want to select has a CSS class or ID.
However, sometimes you need to select a specific element that doesn’t have a class or ID, and there’s no easy way to add a class or ID to the element in the markup. This can happen when using a CMS with a fixed HTML template, or when working with user-created content.
In this situation, you may be able to narrow down the selection by looking at the HTML attributes of the element that you want to select. For example, you could select:
- An image based on its
src
attribute - A link based on its
href
attribute - All form
input
fields that have atype="checkbox"
attribute
…and so on.
jQuery gives you many selectors that you can use to select elements by attribute:
Selector | Description | Example |
---|---|---|
Has Attribute | Selects element(s) that contain the specified attribute, regardless of the attribute’s value. | $("div[attributeName]") |
Attribute Equals | Selects element(s) that contain the specified attribute with the specified value. | $("div[attributeName='value']") |
Attribute Not Equal | Selects element(s) that either don’t contain the specified attribute, or do contain the specified attribute but the attribute’s value doesn’t match the specified value. | $("div[attributeName!='value']") |
Attribute Starts With | Selects element(s) that contain the specified attribute, where the attribute’s value starts with the specified string. | $("div[attributeName^='value']") |
Attribute Ends With | Selects element(s) that contain the specified attribute, where the attribute’s value ends with the specified string. | $("div[attributeName$='value']") |
Attribute Contains | Selects element(s) that contain the specified attribute, where the attribute’s value contains the specified string anywhere in the value. | $("div[attributeName*='value']") |
Attribute Contains Word | Selects element(s) that contain the specified attribute, where the attribute’s value contains the specified word. A “word” in an attribute value is a sequence of non-space characters. | $("div[attributeName~='value']") |
Attribute Contains Prefix | Selects element(s) that contain the specified attribute, where the attribute’s value either equals the specified string, or starts with the specified string followed by a hyphen. | $("div[attributeName|='value']") |
You can combine multiple attribute selectors to further narrow a selection. For example:
// Select only images that have a width of 200 pixels and a height of 300 pixels
var selectedImages = $("img[width=300][height=200]");
The Attribute Contains Prefix selector probably sounds a little pointless, but it’s designed to handle language attributes, such as lang="en"
and lang="en-US"
.
Selecting elements by content
If you can’t narrow down your selection with the basic or attribute selectors, you can delve into an element’s content to determine if it should be selected or not. jQuery gives you 4 selectors for this purpose:
Selector | Description | Example |
---|---|---|
:contains() |
Selects element(s) that contain the specified text. The text can be in the element itself, or in any element inside the element. Note that :contains() is case-sensitive: "Hello" won’t match "hello" . |
// Select all divs containing "myText": |
:has() |
Selects element(s) that contain 1 or more elements that match the specified selector string. The selector looks for matching elements anywhere inside an element β children, grandchildren, and so on. | // Select all divs containing paragraphs: |
:parent |
Selects element(s) that contain other elements or text nodes. | // Select all divs that contain something: |
:empty |
Selects element(s) that don’t contain other elements or text nodes. | // Select all divs that don't contain anything: |
The following examples show how to use :contains()
, along with a class selector, to select only paragraphs of a certain class that contain a certain string (or strings) of text:
// Select all paragraphs that have a class of "intro"
// and that contain the text "MegaWidget"
var selectedElements = $("p.intro:contains('MegaWidget')");
// Select all paragraphs that have a class of "intro"
// and that contain both "MegaWidget" and "WonderWidget"
var selectedElements = $("p.intro:contains('MegaWidget'):contains('WonderWidget')");
Selecting elements by hierarchy
Another way to select elements in jQuery is to look at how elements relate to each other in the page. You’re probably familiar with many of these selectors from working with CSS:
Selector | Description | Example |
---|---|---|
Child | Selects element(s) that are children (that is, direct descendants) of the specified parent(s). | // Select all list elements with a class of "highlight" that are children of the list with ID "nav": |
Descendant | Selects element(s) that are descendants (children, grandchildren, and so on) of the specified ancestor(s). This is a more general form of the Child selector. | // Select all links anywhere inside the list with ID "nav": |
Next Adjacent | Selects the element that immediately follows another element, where both elements are children of the same parent. | // Select all paragraphs that immediately follow an H1 heading: |
Next Siblings | Selects the element(s) that follow another element, where both elements are children of the same parent. This is a more general form of the Next Adjacent selector. | // Select all table cells after the cell that contains the word "Hello": |
First Child | Selects element(s) that are the first child of their parent. | // Select the first item in all lists in the page: |
Last Child | Selects element(s) that are the last child of their parent. | // Select the last item in all lists in the page: |
Nth Child | Selects element(s) that are the nth child of their parent (see note below). | // Select the third item in all lists in the page: |
Only Child | Selects element(s) that are the only child of their parent. | // Select only items in single-item lists: |
As well as specifying numbers with :nth-child()
, you can also specify even
(to match all even-numbered children), odd
(to match all odd-numbered children), or an equation (for example, "li:nth-child(3n+2)"
selects every 3rd child list item, beginning at the second). Find out more about :nth-child()
in the CSS Level 3 spec.
The following example selects the first cell of all the odd rows in a table that has an id
of "myTable"
:
var selectedElements = $("table#myTable tr:nth-child(odd) > td:first-child");
Selecting form fields
Form elements have some specific properties that can make them slightly trickier to select. For example, checkboxes, along with many other field types, are all input
elements, so to select the checkboxes in the form you’d need to use $("input[type='checkbox']")
.
Similarly, identifying the selected items in a select
list, or the checked checkboxes in a form, can be tedious.
Fortunately, jQuery provides a number of useful form-specific selectors to make life easy:
Selector | Description | Example |
---|---|---|
:button |
Selects all form buttons. | $("input:button") |
:checkbox |
Selects all checkboxes. | $("input:checkbox") |
:file |
Selects all file upload fields. | $("input:file") |
:image |
Selects all image input fields. | $("input:image") |
:password |
Selects all password fields. | $("input:password") |
:radio |
Selects all radio buttons. | $("input:radio") |
:reset |
Selects all form reset buttons. | $("input:reset") |
:submit |
Selects all form submit buttons. | $("input:submit") |
:text |
Selects all text input fields. | $("input:text") |
:input |
Selects all form fields, including input , textarea , and select elements. |
$(":input") |
:checked |
Selects all checked checkboxes and radio buttons. | $("input:checked") |
:selected |
Selects all selected option elements. |
$("option:selected") |
:disabled |
Selects all disabled form fields. | $("input:disabled") |
:enabled |
Selects all enabled form fields. | $("input:enabled") |
As well as writing, for example, $("input:checkbox")
to select all checkboxes in the page, you could just write $(":checkbox")
. However, $("input:checkbox")
is faster, since jQuery can use the internal JavaScript function getElementsByTagName()
to quickly reduce the scope of the search to just input
elements. This is true for jQuery in general β to keep your code fast, always restrict the scope of your selectors where possible. For example, $("*")
is very slow, since jQuery has to find every single element in the page.
The following example looks for the form that has an action
attribute of "mailform.php"
, then selects all the checked radio buttons in the form:
var selectedElements = $("form[action='mailform.php'] input:radio:checked");
Selecting elements by their position
Occasionally you want to select an element that is in a known position within a set of previously-selected elements. For example, you may want to select the first paragraph that has a class of "myClass"
. To give a more complex example, you might want to find all list items within a list that have a class of "myClass"
, then select the 5th list item from that set.
jQuery gives you 7 selectors that you can use to narrow down your selection based on element position:
Selector | Description | Example |
---|---|---|
:first |
Selects the first element within the set of currently-selected elements. | // Select the first paragraph that has a class of "myClass": |
:last |
Selects the last element within the set of currently-selected elements. | // Select the last paragraph that has a class of "myClass": |
:eq() |
Selects a single element within the set of currently-selected elements. You select the element by supplying an index number (0 = the first element, 1 = the second, and so on). |
// Select the 3rd paragraph that has a class of "myClass": |
:lt() |
Selects elements within the set of currently-selected elements that occur before the specified index. For example, if you specify an index of 2 (i.e. the 3rd element) then the first 2 elements (at indices 0 and 1) are returned. |
// Select the first 2 paragraphs that have a class of "myClass": |
:gt() |
Selects elements within the set of currently-selected elements that occur after the specified index. For example, if you specify an index of 2 (i.e. the 3rd element) then all elements after the 3rd element are returned. |
// Select all paragraphs that have a class of "myClass", except for the first 3: |
:even |
Selects all elements with even indices within the set of currently-selected elements. Note that, since the indices start from zero, this is actually the 1st element, 3rd element, and so on. | // Select the 1st, 3rd, 5th, and so on paragraphs that have a class of "myClass": |
:odd |
Selects all elements with odd indices within the set of currently-selected elements. Note that, since the indices start from zero, this is actually the 2nd element, 4th element, and so on. | // Select the 2nd, 4th, 6th, and so on paragraphs that have a class of "myClass": |
Note that these selectors do not work in the same way as :first-child
, :last-child
, and so on. For example, li.myClass:first-child
selects only list items of class "myClass"
that also happen to be the first item in their respective lists. li.myClass:first
, on the other hand, finds all list items in the page that have a class of "myClass"
, then selects the first list item in that set of results.
The following example selects all table cells in the first 2 rows of the table that has an ID of "myTable"
:
var selectedElements = $("table#myTable tr:lt(2) > td");
Other useful jQuery selectors
If none of the above selectors helps you find the elements you need, try one of these handy selectors:
Selector | Description | Example |
---|---|---|
:not() |
Selects all elements that don’t match the given selector. | // Select all paragraphs that don't have a class of "myClass": |
:animated |
Selects all elements that are currently being animated by jQuery (for example, being faded in or out). | // Select any divs that are currently being animated: |
:hidden |
Selects all elements that are hidden. An element is considered “hidden” if its display property is set to "none" , if it’s a form field of type "hidden" , if its width and height have been set to zero, or if one of the elements that contain the element is hidden. However, an element is not considered “hidden” just because its visibility property is set to "hidden" . |
// Select all hidden paragaphs that have a class of "myClass": |
:visible |
Selects all elements that are visible. This is the opposite of :hidden . |
// Select all visible paragaphs that have a class of "myClass": |
:header |
Select all heading elements (h1 , h2 and so on). |
// Select the headings that have a class of "myClass": |
The following example selects all heading elements in the page, except h1
(level 1) headings:
var selectedElements = $(":header:not(h1)");
Summary
In this article you’ve looked at how to select elements using jQuery selectors. You’ve explored the following types of selectors:
- Basic selectors, which you’ll use most of the time
- Attribute selectors for selecting elements based on their attribute names and values
- Content selectors, which let you select elements based on their content
- Hierarchy selectors, which you can use to select elements based on their relationships to other elements in the page
- Form field selectors, which provide an easy way to select different types of form field elements
- Position selectors for selecting elements according to their position in a set of elements
- Miscellaneous selectors, such as
:not()
for selecting elements that don’t match a selector, and:animated
for selecting animated elements
Now that you know how to select elements with jQuery, you can start manipulating those elements. I’ll show how to do just that in the next few tutorials.
Happy coding!
biraj says
Fundamentals!!
Good and Easy to start.
Kep it up.
matt says
Thanks for your kind words biraj. Glad you liked the tutorial π
Matt
csirmon23 says
I know this is a year old, but I just wanted to say thanks for a really helpful post. This is a great reference tool for me as I learn jQuery! π
matt says
@csirmon23: Thanks for your feedback – I’m glad you found the article helpful. Good luck with jQuery π