Element selection with jQuery

Last updated .

Previous chapter

First chapter

To perform an element selection you use the jQuery function, which returns a jQuery object, which is a collection containing the selected elements. The syntas is as follows:

var $selection = jQuery(selector, context);
selectorA query string expression.
contextOptional. A reference to a page element or a jQuery expression identifying the query context.
return valueA jQuery object containing the selected elements.

jQuery adopts the symbols used in CSS to denote id, class, tagname etc. This is reflected in the query syntax.

The universal selector

The universal selector selects all elements on the page. The syntax is: *. An example:

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"></meta> <title></title> </head> <body> <script src="jquery-2.1.4.js"></script> <p>A paragraph with <a href="x.html">A link</a></p> <script> var $selection = jQuery("*"); console.log($selection.length); // 9 console.log($selection[7].innerHTML); // A link </script> </body> </html>

In this example, all 9 elements on the page, not including the doctype element, are selected by using the universal selector - the asterisk. The set of elements are retrieved in the order in which they appear in the document. Selecting all elements is probably not terribly useful, selecting a subset based on various criteria is more to the point.

Selection based on element ID

Nothing prevents you from assigning the same ID to more than one element on the same page, but you should not do this. jQuery uses the # symbol to denote selecting by ID. The syntax is: #ID. Using this symbol you will obtain an element set of 0 or 1 elements matching the ID:

<p id="p1">A paragraph</p> <p id="p2">Another paragraph</p> <script> var $selection = jQuery("#p2"); console.log($selection.length); // 1 console.log($selection[0].innerHTML) // Another paragraph </script>

Selection based on class name

Using this syntax, elements with a certain class name are selected. jQuery uses the . symbol to denote selecting by ID. The syntax is: .className. As an example, consider a document, where classes class1 and class2 are defined:

<p class="class1">A paragraph</p> <p class="class1 class2">Another paragraph</p> <p class="class2">A third paragraph</p> <script> var $selection = jQuery(".class2"); console.log($selection.length); // 2 console.log($selection[0].innerHTML) // Another paragraph </script>

The first two p elements are selected, because they use the class2 class.

To select elements that have a combination of classes, concatenate the class names in the search string:

<p class="class1">A paragraph</p> <p class="class1 class2">Another paragraph</p> <p class="class2">A third paragraph</p> <script> var $selection = jQuery(".class2.class1"); console.log($selection.length); // 1 console.log($selection[0].innerHTML) // Another paragraph </script>

The second p element is selected, because it is the only element using both the class1 and class2 classes. Note that the order in which the class names are listed is immaterial.

Selection based on tag name

Using this syntax, elements with a certain tag name are selected. The syntax is: tagName. As an example, consider the following HTML snippet:

<p>A paragraph</p> <p>Another paragraph</p> <div>A third paragraph</div> <script> var $selection = jQuery("p"); console.log($selection.length); // 2 console.log($selection[0].innerHTML) // A paragraph </script>

The example selects the two p elements.

It is possible to combine the tag selector with other selectors, e.g. the class selector, as shown in the following example. The tag name must be specified first:

<p class="class1">A paragraph</p> <p class="class2">Another paragraph</p> <div class="class1">A third paragraph</div> <script> var $selection = jQuery("p.class1"); console.log($selection.length); // 1 console.log($selection[0].innerHTML) // A paragraph </script>

The example selects the one and only p element with the class1 class.

Combining selectors

It is possible to combine selectors, by separating them with commas:

<p class="class1">A paragraph</p> <p class="class2">Another paragraph</p> <div class="class1">A third paragraph</div> <div class="class2">A fourth paragraph</div> <div class="class3">A fifth paragraph</div> <script> var $selection = jQuery("p, div.class1, .class2"); console.log($selection.length); // 4 console.log($selection[0].innerHTML) // A paragraph </script>

In the above example, four elements are selected, namely both p elements and the first two div elements. Note that no element is selected more than once, although it may satisfy more than one criteria.

Hierarchical selectors

Hierarchical selectors lets you select elements based on their relationship to other elements in the DOM tree. For example, all descendants of an element:

<div id="p1">A paragraph with a link: <a>Link 1</a> <ul> <li><a>Link 2</a></li> <li><a>Link 3</a></li> </ul> </div> <script> var $selection = jQuery("#p1 a"); console.log($selection.length); // 3 console.log($selection[2].innerHTML) // Link 3 </script>

In the above example, the element with the id p1 serves as the base of the selection. All its descendants (denoted by the space character) of type a are selected. (An element D is descendant of an element P if the latter element can be found by traversing the DOM tree upwards from D.)

The four types of hierarchical selectors can be summarized as follows:

SelectorDescription
A BSelects elements with tag name B that are descendants of A
A>BSelects elements with tag name B that are children of A
A+BSelect the one element with tag name B that is the immediately following sibling of A
A~BSelect the elements with tag name B that are the next siblings of A

The + and ~ selectors warrant an explanation. The + selector will never select more than one element. Consider the following example:

<p id="p1">p1</p> <div id="div1" class="1">div1</div> <p id="p2">p2</p> <p id="p3">p3</p> <p id="p3">p4</p> <script> var $selection = jQuery("#p2 + p"); console.log($selection.length); // 1 console.log($selection[0].innerHTML) // p3 </script>

the p3 element is selected because it is the next sibling of p2 and is of type p. The query #p1+p would have selected nothing, because the next sibling of p1 is a div, not p. It is also possible to use the asterisk for the second term, like this: #p1+*, in which case the div would be selected. In contrast, the ~ selector selects any number of elements. Using the query #p1~p in the above example would select the three p elements that are siblings of p1 and are found after it.

Attribute selectors

Attribute selectors let you select elements based on an attribute. An attribute selector is enclosed in square brackets. An arbitrary number of attribute selectors can be combined by entering each one in square brackets, thus AND'ing them together. For example, the query p[title='p1'][lang='en'] selects all p elements with a title of 'p1' and lang equal to 'en'. Another example:

<script src="jquery-2.1.4.js"></script> <p id="e1" class="class1" title="raca">p1</p> <div id="e2" class="class1" title="abrac" lang="en">div1</div> <p id="e3" class="class1" title="bra" lang="da">p2</p> <p id="e4" class="class1" title="abracadabra" lang="en">p3</p> <p id="e5" class="class1" title="abra" lang="en">p4</p> <script> var $selection = jQuery(".class1[title *= 'rac'][lang]"); console.log($selection.length); // 2 console.log($selection[1].innerHTML) // p3 </script>

The above query uses the *= operator to select all class1 elements with a lang attribute and a title attribute that contains the string "rac". This selects the elements e1 and e4.

There are eight types of attribute selector:

SelectorDescription
[A]Selects elements with an attribute A
[A='S']Selects elements with an attribute A with the value S
[A!='S']Selects elements not with an attribute A with the value S
[A*='S']Selects elements with an attribute A whose value contains the string S
[A^='S']Selects elements with an attribute A whose value starts with the string S
[A$='S']Selects elements with an attribute A whose value ends with the string S
[A~='S']Selects elements with an attribute A whose value contains the string S delimited by the space character
[A|='S']Selects elements with an attribute A whose value equals S or S-

Note that attribute selectors operate on attributes as they occur in the initial markup, not on the current values in the DOM. For example, if a button was initially enabled and then disabled through code, it would not be selected in the query button[disabled].

Position selectors

The position selectors select elements on the basis of their position (the 0-based index) in the document. These selectors use the : character. An example that selects all list items after the first two:

<ul id="ul0"> <li>Item 0.0</li> <li>Item 0.1</li> <li>Item 0.2</li> </ul> <ul id="ul1"> <li>Item 1.0</li> </ul> <script> var $selection = jQuery("li:gt(1)"); console.log($selection.length); // 2 console.log($selection[1].innerHTML) // Item 1.0 </script>

Rather than selecting from the whole document, it is normally more useful to combine a position selector with another selector to select from a narrower context. For example, to select even-indexed list items only from the first list:

<ul id="ul0"> <li>Item 0.0</li> <li>Item 0.1</li> <li>Item 0.2</li> </ul> <ul id="ul1"> <li>Item 1.0</li> </ul> <script> var $selection = jQuery("#ul0 li:even"); console.log($selection.length); // 2 console.log($selection[1].innerHTML) // Item 0.2 </script>

There are seven position selectors:

SelectorDescription
:firstSelects the first matching element
:lastSelects the last matching element
:evenSelects even-indexed elements
:oddSelects odd-indexed elements
:eq(n)Selects the element with index n
:gt(n)Selects elements with index greater than n
:lt(n)Selects elements with index less than n

Child selectors

The child selectors let you select child elements based on their relation to the parent. It has the format type:selector, where type is a statement that narrows the kind of child elements to search. The type part can be omitted, in which case the universal selector is understood. Confusingly, where these iterators employ the concept of index, it is 1-based!. An example:

<p> <span class="class2">span 1.1</span> <em class="class2">em 1.2</em> <span class="class2">span 1.3</span> <em class="class1">em 1.4</em> <em class="class2">em 1.5</em> <em class="class2">em 1.6</em> </p> <p> <span class="class2">span 2.1</span> <em class="class2">em 2.2</em> <span class="class2">span 2.3</span> <em class="class2">em 2.4</em> <img class="class2"></img> </p> <script> var $selection = jQuery("p .class2:nth-of-type(2)"); console.log($selection.length); // 3 console.log($selection[2].innerHTML) // em 2.4 </script>

In the above example, the children of p elements are searched, and the second occurrence of each type of element (here: span, em, img) is selected if it has the class class2.

<p> <span class="class2">span 1.1</span> <span class="class2">span 1.2</span> <span class="class2">span 1.3</span> <span class="class2">span 1.4</span> <span class="class2">span 1.5</span> <em class="class2">em 1.6</em> <span class="class2">span 1.7</span> <span class="class2">span 1.8</span> <span class="class2">span 1.9</span> <span class="class2">span 1.10</span> </p> <p> <span class="class2">span 2.1</span> <em class="class2">em 2.2</em> <span class="class2">span 2.3</span> <em class="class2">em 2.4</em> <img class="class2"></img></p> <script> var $selection = jQuery("p span:nth-child(3n)"); console.log($selection.length); // 3 console.log($selection[1].innerHTML) // span 1.9 </script>

In the above example, every third child of p elements are selected, if they are of type span. The snippet is an example of using a formula (3n) in the query to select every third element. A formula of 4n+1 would select items 5, 9, 13, etc. It is also posssible to use the words even and odd for the parameter.

The child selectors can be summarized as follows:

SelectorDescription
:first-childSelects the first child
:last-childSelects the last child
:nth-child(p)Selects children satisfying the parameter p (see below), counting from the first child
:nth-last-child(p)Selects children satisfying the parameter p (see below), counting from the last child
:only-childSelects children with no siblings
:first-of-typeSelects the first child of a given type
:last-of-typeSelects the last child of a given type
:nth-of-type(p)Selects children of a certain type satisfying the parameter p (see below), counting from the first child
:nth-last-of-type(p)Selects children of a certain type satisfying the parameter p (see below), counting from the last child
:only-of-typeSelects children of a certain type with no siblings

The p parameter can be a numeric index (1-based), the keywords even or odd or an equation of the form an+b, where you supply the numbers a and b.

Selectors related to input elements

These selectors also use the : character and operate on the current state of the elements. For example, such a selector lets you select button elements that are currently disabled, irrespective of the initial state. An example that selects checked radio boxes inside a form:

<form id="form1"> <input type="radio" value="Option 1"></input> <input type="radio" value="Option 2" checked="checked"></input> <input type="checkbox" value="Checkbox 1" checked="checked"></input> </form> <script> var $selection = jQuery("#form1 :radio:checked"); console.log($selection.length); // 1 console.log($selection[0].value) // Option 2 </script>

As the example shows, these selectors can be chained to fine-tune the query. The input-related selectors can be summarized as follows:

SelectorDescription
:checkedSelects radioboxes or checkboxes in a checked state or option elements in a selected state
:disabledSelects disabled elements
:enabledSelects enabled elements
:focusSelects elements with focus
:selectedSelects option elements in a selected state
:buttonSelects button elements and input elements of type button, submit or reset
:checkboxSelects checkbox input elements
:fileSelects file input elements
:imageSelects image input elements (not img elements)
:inputSelects input, select, button and textarea elements
:passwordSelects password input elements
:radioSelects radio input elements
:resetSelects reset input elements and button of type reset
:submitSelects submit input elements and button of type submit
:textSelects text input elements

Content filters

These selectors select elements on the basis of their contents, be it text or child nodes. An example:

<p> <span>span 1.1</span> <span>using jquery-2.1.4.js</span> </p> <p> using jquery-2.1.4.js </p> <script> var $selection = jQuery("p:contains('jquery')"); console.log($selection.length); // 2 console.log($selection[1].tagName) // p </script>

The above example selects both p elements, because they both contain the text "jquery". The second paragraph is also selected, even though the text "jquery" is contained in a descendant span element.

The has selector is also worthy of an example:

<p id="p1"> <span><a src="http://jquery.com">jQuery</a></span> </p> <p id="p2"> <span><a src="http://msdn.com">MSDN</a></span> </p> <script> var $selection = jQuery("p:has(a[src*='jquery'])"); console.log($selection.length); // 1 console.log($selection[0].id) // p1 </script>

The has selector selects elements with one or more descendants that satisfy the subquery. In the example, p elements are selected if a descendant anchor element has a src attribute containing the string "jquery".

The content filters:

SelectorDescription
:contains(text)Selects elements containing the specified text
:has(subquery)Selects elements containing one or more descendante satisfying the subquery
:emptySelects elements with no children
:parentSelects elements with children

Various selectors

This section details a number of selectors that did not fit into one of the above categories. Most of them are pretty self-explanatory:

SelectorDescription
:hiddenSelects elements that don't occupy space (have no layout box)
:visibleSelects elements that do occupy space (have a layout box)
:animatedSelects elements under animation
:headerSelects header elements (h1, h2, etc)
:lang(l)Selects elements with a lang attribute with the specified value
:not(subquery)Selects elements that do not satisfy the subquery
:targetSelects elements whose id match the target fragment identifier of the document URI
:rootSelects the document root element

The :hidden selector is a bit confusing, because it does not consider elements with the style visibility:hidden as hidden. Instead, it considers as hidden those elements that have display:none or have 0 width and height:

<p id="p1" style="visibility:hidden;">p1</p> <p id="p2" style="visibility:collapse;">p2</p> <p id="p3" style="display:none;">p3</p> <p id="p4" style="display:block;width:0px;height:0px;">p4</p> <p id="p5"></p> <p id="p6">p6</p> <script> var $selection = jQuery("p:hidden"); console.log($selection.length); // 2 console.log($selection[0].id) // p3 </script>

Extending jQuery selectors with custom filter functions

Sometimes, the tools in the jQuery toolbox do not quite suffice. Luckily, jQuery is extensible in that you can write your own selector functions and then use them just like any other jQuery selector. jQuery has an expr property which in turn has a : property. The latter contains jQuery’s native filters and you can use it to add your own. A custom selector is created by passing an anonymous function to the jQuery.expr.createPseudo method. The function that you define must accept a single parameter - you get to choose its name - that you may use or not. Inside the function, define a function responsible for the actual filtering. That function receives three parameters, of which the first one is a reference to a DOM element. You must return a boolean indicating if that element satisfies the filter. As an example, imagine that, for some reason, you need to select elements with tabIndex higher than some (variable) value. To this end, one can create a "tabIndexHigherThan" filter function that will be used in the usual jQuery way, as :tabIndexHigherThan(valueParam). An example:

<form id="form2"> <input id="i1" tabindex="1"></input> <input id="i2" tabindex="0"></input> <input id="i3" tabindex="3"></input> <input id="i4" tabindex="117"></input> </form> <script> jQuery.expr[":"].tabIndexHigherThan = jQuery.expr.createPseudo(function (filterParam) { var param = parseInt(filterParam); return function (element, context, isXml) { return element.tabIndex > param; } } ); </script> <script> var $selection = jQuery("*:tabIndexHigherThan(2)"); console.log($selection.length); // 2 console.log($selection[0].id); // i3 console.log($selection[1].id); // i4 </script>

In this example, all elements with tabindex higher than 2 are selected. The comparison is numeric, and that is the reason why the built-in jQuery selectors could not do the job.

Next chapter