Selection with jQuery3.1
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
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); console.log(x);
- Tag selection - the type of the tag - e.g.
- Class selection - .class_name - e.g.
- ID selection - #id - e.g
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"); x.remove();
x = jQuery("p"); x.remove();
The second method is to use the jQuery function
x = jQuery("p"); x.eq(0).remove();
The benefit of using the
x = jQuery("p"); i = x.length - 2; x[i].remove();
eq method it is possible to do this in a much simpler syntax:
x = jQuery("p"); x.eq(-2).remove();