Translated from jQuery Cookbook (O 'Reilly 2009) Chapter 2 Selecting Elements with jQuery, 2.0 Introduction
JQuery's core is its selector engine, which filters out elements from documents by name, attribute, status, and so on. Because CSS is widely used, it is natural to use CSS selector syntax in jQuery. In addition to supporting selectors in most CSS1-3 specifications, jQuery also adds a number of custom selectors to select elements based on some special States; at the same time, we can also write our own selectors.
The simplest way to locate an element or some elements in the document is to use jQuery to encapsulate functions and CSS selectors, such:
JQuery ('# content p ');
// Select all the elements in the # content element. After selecting the elements, you can call the jQuery Method on these elements. For example, add the selected class attribute to all selected link elements:
JQuery ('# content p '). addClass ('selected'); jQuery provides many methods to traverse the DOM tree to help select elements, such as next (), prev (), and parent. These methods use a selector expression as its unique parameter to filter the selected element set. Therefore, except jQuery (...), CSS selectors are also used in many places.
When building a selector, you can follow the rule of simplifying the preparation of the selector as much as possible to improve its performance. The more complex the selector string is, the longer it takes to process jQuery. JQuery uses the native DOM method of the browser to select elements. Therefore, directly using selector to select elements is just an abstract encapsulated result. There is nothing wrong with using the selector directly, but it is very important to understand the execution performance of the written code. Here is an example of excessive selector usage:
JQuery ('body div # wrapper div # content'); more precise positioning does not mean faster code execution. The preceding selector can be rewritten:
JQuery ('# content'); compared with the previous example, this code works the same, but it saves a lot of performance overhead. It is worth noting that sometimes we can further improve the performance by specifying the context of the selector.