Selecting DOM Elements Using Selectors and the jQuery Function - J Query

You need to select a single DOM element and/or a set of DOM elements in order to operate on the element(s) using jQuery methods.


jQuery provides two options when you need to select element(s) from the DOM. Both options require the use of the jQuery function (jQuery() or alias $()). The first option, which uses CSS selectors and custom selectors, is by far the most used and most eloquent solution. By passing the jQuery function a string containing a selector expression, the function will traverse the DOM and locate the DOM nodes defined by the expression.
As an example, the following code will select all the <a>elements in the HTML document:

If you were to run this HTML page in a web browser, you would see that the code executes a browser alert() that informs us that the page contains six <a>elements. I passed this value to the alert() method by first selecting all the <a>elements and then using the length property to return the number of elements in the jQuery wrapper set. You should be aware that the first parameter of the jQuery function, as we are using it here, will also accept multiple expressions. To do this, simply separate multiple selectors with a comma inside the same string that is passed as the first parameter to the jQuery function. Here is an example of what that might look like:

Our second option for selecting DOM elements and the less common option is to pass the jQuery function an actual JavaScript reference to DOM element(s). As an example, the following code will select all the <a>elements in the HTML document. Notice that I’m passing the jQuery function an array of <a>elements collected using the get Elements By TagName DOM method. This example produces the same exact results as our previous code example:

The heavy lifting that jQuery is known for is partially based on the selector engine, Sizzle, that selects DOM element(s) from an HTML document. While you have the
option, and it’s a nice option when you need it, passing the jQuery function DOM references is not what put jQuery on everyone’s radar. It’s the vast and powerful options available with selectors that make jQuery so unique.
Throughout the rest of the book, you will find powerful and robust selectors. When you see one, make sure you fully understand its function. This knowledge will serve you well with future coding endeavors using jQuery.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics