To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Part 3.1Selection with jQuery

jQuery's strongest feature is the way that selection is made. The word selection refers to the selection of elements.

As described in the HTML course, elements are what compose a web document.

The jQuery library

To access the jQuery functions the jQuery function (stored as a variable also called jQuery) is used then a reference to an element:


This selection returns a jQuery object with all elements selected thus it can be chained.

Run the following code sample to see how this works:

x = jQuery(this);


Selection is not just achieved by passing in variables. Strings can be passed the same way that they are passed to the JavaScript document.querySelectorAll method works (more in JavaScript course). This means there are three main types of element selection:

  • Tag selection - the type of the tag - e.g. p
  • Class selection - .class_name - e.g. .example_class
  • ID selection - #id - e.g #example_id

It is outwith the scope of this course to cover the different forms of selection, however it is described within the CSS course.

The following example shows selection of the HTML object of the document. To prove it works, it will also remove the HTML element (and as a side effect, the whole page will disappear):

x = jQuery("html");

Since selection can often return an array, selecting an index from this array can be achieved in two ways. The first of those is using the JavaScript square brackets syntax:

x = jQuery("p");

The second method is to use the jQuery function eq:

x = jQuery("p");

The benefit of using the eq method over the standard JavaScript syntax is that it allows you to quickly find from the reverse by applying a negative value. Assume the following:

x = jQuery("p");
i = x.length - 2;

With jQuery's eq method it is possible to do this in a much simpler syntax:

x = jQuery("p");


The jQuery library is a well-designed library that allow chaining of methods. This means instead of writing a jQuery selector for every effect that is needed, only one selection is required. Without chaining, each of these

x = jQuery(".class1");
x.css({"background-color" : "red", "color" : "white"});

But using chaining, this can be simplified to:

x = jQuery(".class1");
x.fadeIn().css({"background-color" : "red", "color" : "white"});
Code previewClose
Feedback 👍
Comments are sent via email to me.