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:

JavaScript
jQuery(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:

JavaScript
x = jQuery(this);
console.log(x);
		

Selection

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):

JavaScript
x = jQuery("html");
x.remove();
		

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:

JavaScript
x = jQuery("p");
x[0].remove();
		

The second method is to use the jQuery function eq:

JavaScript
x = jQuery("p");
x.eq(0).remove();
		

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:

JavaScript
x = jQuery("p");
i = x.length - 2;
x[i].remove();
		

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

JavaScript
x = jQuery("p");
x.eq(-2).remove();
		
Code previewClose
Feedback 👍
Comments are sent via email to me.