Tech and Media Labs
This site uses cookies to improve the user experience.




jQuery Selectors

Jakob Jenkov
Last update: 2015-01-19

jQuery selectors are used to select DOM elements in the HTML page. Most jQuery code starts with a jQuery selector. The code selects one or more HTML elements and then traverse the DOM elements using the jQuery traversal features, manipulate the DOM elements via the jQuery DOM manipulation features, add event listeners to them via the jQuery event features, or add effects to them via the jQuery effects features.

jQuery contains a wide range of selectors which can select HTML elements based on their element name, id, attribute values, visibility, element order and many other criteria. This jQuery selector tutorial will cover the most commonly used selectors. For a full list of all jQuery selectors, see the following page in the official jQuery documentation:

http://api.jquery.com/category/selectors/

jQuery Selector Overview

A jQuery selector is a string which specifies which HTML elements to select. The selector string is passed to the $() or jQuery() selection function which returns a collection of the selected elements.

The jQuery selector syntax is the same as CSS selectors, so if you are familiar with CSS selectors you will learn jQuery selectors very quickly.

jQuery lets you select elements based on the following criteria:

  • Element name (e.g. 'p', 'a', 'div' etc.)
  • Element id
  • Element CSS class
  • Element attributes
  • Element visibility
  • Element order
  • Form Fields
  • Element parents or children
  • Combinations of the above

I will cover each of these options in the sections below.

jQuery Selector Example

To get you started, let me show you a simple jQuery selector example:

var theDiv = $("#theDiv");

This example selects the div element with the id theDiv, meaning the div element which has an id attribute with the value theDiv.

The $() and jQuery Functions

The $() returns a jQuery enhanced set of elements. This jQuery enhanced set of elements contains a lot of utility functions which can be applied to all elements in the set. For instance, here is how you set a CSS class on all the selected elements in the set:

var theDiv = $("#theDiv");

theDiv.addClass("newCssClass");

This example sets the CSS class newCssClass on all elements in the set. Since the example only selects a single element, only one element will get the new CSS class.

A shorter way of writing the above code is:

$("#theDiv").addClass("newCssClass");

Notice how the addClass() function is chained directly to the $() call.

Many of the utility functions on the jQuery enhanced selection set return the selection set itself. That means that you can chain method calls on the selection set, like this:

$("#theDiv").addClass("newCssClass")
            .css("border", "1px solid #cccccc")
            .css("background-color", "#f0f0f0")
    ;

As hinted, this technique is called method chaining. In the JavaScript world an API designed to work with method chaining is also referred to as a "fluent" API. jQuery's fluent style API makes it very easy to make changes to the DOM.

Instead of the $() function you can also use the jQuery() function. The two functions do exactly the same thing, but sometimes you might be using other JavaScript libraries which also define a $() function. In that case, use the jQuery() function instead.

The many utility functions on the selection set are covered in separate texts in this jQuery tutorial trail. For instance, there are traversal functions, CSS manipulations functions, DOM manipulation functions, various effects (like fading and scrolling of elements), event listener functions, and much more.

The find() Function

The selection set returned by the $() or jquery() functions contains a function called find(). The find() function can be used to find descendants of elements in the selection set. The find() function takes a selector string as parameter which indicates what elements to find in the selection set.

The find() function only searches through the descendants of the elements in the selection set. That is, the children and their children etc. of the elements in the selection set.

Here is a jQuery find() example:

$("ul").find("li");

This example will find all li elements inside all ul elements. This is similar to using the descendant selector, like this:

$("ul li");

The find() function returns a new selection set. It does not modify the selection set it was called on.

The selection set also has a children() function which works similarly to find() except children() can be used both with and with arguments (selector string), and it only searches through the immediate children of the elements in the selection set.

The filter() Function

The selection set also contains a function called filter(). The filter() function is similar to find, except it also works on the elements in the selection set, and not just their children and descendants.

The filter() function takes a selector string or a function which is used to filter the selection set. The filter() function returns a new selection set. It does not modify the selection set it was called on. Here is a jQuery filter() example:

$("ul").filter(".taskList");

This example first selects all ul elements, and then filters that collection to return all elements in the selection set (including descendants of the selected ul elements) which contains the CSS class taskList.

You can also pass a filter function to filter(). Here is a filter() example which takes a filter function as parameter:

$("a").filter(function() {
    return $(this).attr("href") !== "undefined" ;
});

This example selects all a elements, and then filters them using a filter function. The filter function returns true if the given a element contains an href attribute.

Inside the filter parameter function the variable this refers to each element from the selection set the filter() function is called on. You can also get the index of the element to inspect, by inserting an index parameter in the filter parameter function. Here is the example from before with and index parameter added.

$("a").filter(function(index) {
    return $(this).attr("href") !== "undefined" ;
});

The has() Function

The selection set also contains a function called has(). The has() function takes a selector string as parameter, just like find() and filter. The has() matches the selector string against all descendants of the elements in the selection set. If an element in the selection set contains a descendant that matches the selector string, then the element having the matching descendant is included in the new selection set returned by has().

Here is a jQuery has() example:

$("div").has("p");

This example first selects all div elements, and then it selects those of the selected div elements which contain one or more p elements.

has() vs find() vs filter()

The three jQuery selection set functions has(), find() and filter() are pretty similar, but there are some important differences in what elements they select.

The has() function only selects elements which are already part of the selection set. It does not select any descendants, even though it uses the descendants to determine what elements to select. In other words, it selects elements that have elements matching the selector (hence the name has()).

The find() function only select descendant elements of the elements in the selection set. All elements matching the given selector will be part of the returned selection set. In other words, it finds matching elements inside the elements in the selection set. Not among the selected elements themselves.

The filter() function selects both elements in the selection set as well as their descendants. In other words, it filters all elements in the selection set and their descendants according to a selector.

Look at the following HTML:

<div>
    <p>Paragraph 1</p>
</div>
<div>
    <p>Paragraph 2</p>
</div>
<div>
    <p>Paragraph 2</p>
</div>

The following three expressions will return different selection sets.

$("div").has   ("p");    
$("div").find  ("p");    
$("div").filter("p");    

$("div").has("div, p"); will select all div elements which contain a p element as descendant. That is the three top level div elements.

$("div").find ("div, p"); will select all p element which are descendants of the three top level div elements. That will be the three child p elements.

$("div").filter("p"); will select all p elements in the selection set, or which are descendants of elements in the selection set. In this example that will also be the three child p elements because the first selection set does not contain any p elements directly (the first selection set only contains the three top level div elements).

Element Name Selector

The element name selector enables you to select elements by their names, means elements of a certain type or kind. For instance, all <a> elements, or <p> elements. Here is a jquery element name selector example:

$('a');

This example selects all a elements, but it doesn't really do anything with the elements. Here is an example that changes the CSS style of all a elements:

$('a').css('background-color', '#00ff00');

This example sets the background color of all a elements to green.

Element Id Selector

The element id selector enables you to select element by their ids. An elements id is specified in its id attribute. The id must be unique in the page, and is case sensitive. Here is a jquery element id selector example:

<script type="text/javascript">

$(document).ready(function() {
    $('#theId').css('background-color', '#00ff00');
});

</script>

<div id="theId">
    text
</div>

This example will select the div element that has the id 'theId', and change its background color to green.

Notice how the id has a # in front of it, inside the jQuery selector. This signals to jQuery that you are selecting an element by its id.

CSS Class Selector

The class selector enables you to select elements based on their CSS class. Here is a jquery class selctor example:

$('.theClass').text();

This example selects all elements which have the CSS class theClass. CSS classes are set via the class attribute of an HTML element. CSS classes can also be set via jQuery. See the text on jQuery & CSS for more info.

Notice how the . in front of the class name in the jQuery select parameter signals to jQuery, that you want to select by CSS class.

Attribute Selectors

The attribute selectors enables you to select elements based on what attributes the elements have, and even based on attribute values. There are several different attribute selectors which I will cover below.

Has Attribute Selector

The "has attribute" selector enables you to select all elements which have a certain attribute, regardless of that attribute's value.

To specify an attribute selector you write the attribute name inside square brackets in the selector string. Here is a jQuery attribute selector example (has attribute):

$('[height]');

This example will select all elements that has a height attribute.

You can combine the attribute selector with other selectors, e.g. the element name selector selector to select all div elements having the attribute height. Here is a element name and has attribute selector example:

$('div[height]');

Attribute Value Equals Selector

The attribute value selector enables you to select elements based on specific attribute values. Here is a jQuery attribute value equals selector example:

$('div[height=200]');

This example selects all div elements with a height attribute value of 200.

You can also enclose the value in quotes, like this:

$('div[height="200"]');

Attribute Value Not Equals Selector

The attribute value selector also enables you to select elements based on attribute value not being equal to a certain value. This is done by putting a ! in front of the = in the select expression. Here is an example:

$('div[height!=200]');

This example selects all div elements that do not have an attribute value of 200. This also includes all div elements without any height attribute at all.

Attribute Value Prefix Selector

The attribute value prefix selector enables you to select elements which contain an attribute with a value that starts with a given value. In other words, where the attribute value contains a certain prefix. Here is a jQuery attribute value prefix selector example:

$('[href|="http://"]');

This example selects all elements with a href attribute where the value starts with http:// .

Attribute Value Contains Selector

The attribute value contains selector enables you to select elements with an attribute where the value contains a certain substring. Here is a jQuery attribute value contains example:

$('[href*="/download/"]');

This example selects all elements which contains the substring /download/ in their href attribute values.

Attribute Value Ends With Selector

The attribute ends with selector enables you to select elements with an attribute where the value ends with a certain substring. Here is a jQuery attribute value ends with selector example:

$('[href$=".pdf"]');

This example selects all elements which have an href attribute where the value ends with .pdf.

Element Visibility Selector

The element visibility selector enables you to select elements based on whether they are visible or not. jQuery contains the following following element visibility selectors:

  • :hidden
  • :visible

Here is a jQuery visibility selector example:

$(':visible');

$(':hidden');

The first line selects all visible elements in the page. The second line selects all hidden elements in the page.

Element Order Selectors

The element order selector makes it possible to select element based on the order in which they appear in the HTML page (in the DOM). For instance, you can select the third div element in the page, or all odd div elements etc.

Here is a jQuery element order selector example:

$('div:first').text();

This example selects the first div element in the page. The order is written after the : in the jQuery selector parameter.

You can use the following order parameters:

  • :first
  • :last
  • :even
  • :odd
  • :eq(index)
  • :gt(index)
  • :lt(index)

:first selects the first element of the given kind.

:last selects the last element of the given kind.

:even selects the even elements of the given kind, meaning the elements that have index 0, 2, 4 etc.

:odd selects the odd elements of the given kind, meaning the elements that have index 1, 3, 5 etc.

:eq() selects the element having the given index, starting from 0. For instance, 'div:eq(3)' selects the 4th div element in the page.

:gt() selects all elements with index greater than the given index. For instance, 'div:gt(1)' selects all div elements with indexes greater than 1.

:lt() selects all elements with index less than the given index. For instance, 'div:lt(2)' selects all div elements with indexes less than 2.

Form Field Selectors

jQuery contains a set of form field selectors which makes it easier to select the various different types of form fields from the DOM. In this section I will cover the most common jQuery form field selectors.

:input Selector

The :input selector enable you to easily select input elements. Here is a jQuery :input example:

$(":input");

This example selects all input fields in the page. Notice the : before the text input. This colon is necessary to not confuse it with a selection based on element name. In this example there might not have been any difference between input and :input, but for several of the form field selectors, there is a difference.

:text Selector

:text selects all input fields of type text. It does not select textarea elements. Here is a jQuery :text selector example:

$(":text");

:radio Selector

The :radio selects all input fields of type radio. That is, all radio button elements. Here is a jQuery :radio selector example:

$(":radio");

:checkbox Selector

The :checkbox selects all input fields of type checkbox. All checkbox elements, in other words. Here is a jQuery :checkbox selector example:

$(":selector");

The :checked selects all input fields of type checkbox or radio which are checked.

:password Selector

The :password selector selects all input elements of type password. Here is a jQuery :password selector example:

$(":password");

:submit Selector

The :submit selector selects all input elements of type submit. That is, all form submit buttons. Here is a jQuery :submit selector example:

$(":submit");

:reset Selector

The :reset selector selects all input elements of type reset. That is, all form reset buttons. Here is a jQuery :reset selector example:

$(":reset");

:file Selector

The :file selector selects all input elements of type file. That is, all file upload fields. Here is a jQuery :file selector example:

$(":file");

Button Selector

The :button selector selects all button elements and input elements of type button. It does not select input elements of type submit. Here is a jQuery :button selector example:

$(":button");

Enabled and Disabled Element Selectors

The :enabled selector selects all elements that are enabled. Likewise, the :disabled selector selects all elements that are disabled. Here are a jQuery :enabled and :disabled selector example:

$(":enabled");

$(":disabled");

Empty Element Selector

The :empty element selector selects all elements which are empty, meaning they have no child elements and no text inside its body (attributes are allowed). Here is a jQuery :empty selector example:

$(":empty");

Contains Text Selector

The :contains selector is used to select elements which contains a certain text. Here is a jQuery :contains example:

$(":contains(Hello World)");

This example selects all elements which contain the text "Hello World".

Target Element Selector

The :target selector selects the element which is the HTML fragment target of the current URL. For instance, if the URL in the browser is:

http://myapp.com/somepage.html#someElement

Then the :target selector will select the element with the id (or name) someElement, because the HTML fragment part of the URL points is #someElement .

Here is a jQuery :target selector example:

$(":target");

All Elements Selector

The * (all elements) selector selects all elements in the HTML document. Since you won't often need that, the * selector is often combined with other selectors. Here is an example of the element name selector and parent / child selector combined with the * selector:

$("div>*");

This example selects all immediate children of all div elements. The div part indicates all div elements. The > part indicates immediate children of what is selected on the left (which is all div elements). The * means all elements. In total, that means all immediate child elements of all div elements.

Parents and Child Selectors

The parent and child selectors enable you to select element based on what parents or ancestors they have, or their order inside their parent elements. You can use the following parent and child selectors to select elements based on their parent - child relationship:

  • :first-child
  • :last-child
  • parent>child

The :first-child selector lets you select the first child of a parent element. Here is jQuery :first-child example:

$('div:first-child');

This example selects the first child of all div elements.

The :last-child selector works the same way as :first-child except it selects the last child of the parent.

The parent>child selector lets you select children of a specific parent element. Here is a jQuery parent>child example:

$('div>p');

This example will select all p elements inside div elements. p elements outside div elements are not selected.

Combining Selectors

You can combine many of the jQuery selectors to create even more powerful selector expressions. To achieve full mastery, you must experiment with combinations yourself, but here I will give you a few examples, so you can get a feeling for how it works.

Here is an example that selects all p elements inside div elements, of div elements having the attribute height set to 300:

$('div[height=300]>p');

The next example enhances the first example, by adding the criteria, that only p elements with the CSS class go should be selected:

$('div[height=300]>p.go');

The third example modifies the previous example, by only selecting the p element with the id p_id:

$('div[height=300]>p#p_id');

As you can see, combining selectors can be used to create powerful, very specific select expressions.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC