Translated from jQuery Cookbook (O'Reilly 2009) Chapter 2 Selecting Elements with jQuery, 2.0 Introduction
The core of jQuery is its selector engine, which is used to filter out elements from the document by name, attributes, status, etc. Due to the widespread use of CSS, using CSS selector syntax in jQuery becomes a natural choice. In addition to supporting most selectors in CSS1-3 specifications, jQuery has also added many custom selectors to select elements based on some special states; at the same time, we can also write our own selectors.
The easiest way to locate an element or elements in a document is to use jQuery wrapper functions and CSS selectors, such as:
<SPAN class=pln>jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'#content p a'</SPAN><SPAN class=pun>);</SPAN><SPAN class=pln> </SPAN><SPAN style="COLOR: #333399" class=com>//选择所有#content元素内的p元素中的a元素</SPAN>
After selecting elements, you can call jQuery methods on these elements. For example, add the selected class attribute to all selected link elements:
<SPAN class=pln>jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'#content p a'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>addClass</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'selected'</SPAN><SPAN class=pun>);</SPAN>
jQuery provides many methods for traversing the DOM tree to help select elements, such as next(), prev(), parent(), etc. These methods accept a selector expression as their only argument to filter the set of selected elements. Therefore, in addition to jQuery(...), CSS selectors are also used in many places.
When building a selector, in order to improve its performance, you can follow a rule: simplify the writing of the selector as much as possible. The more complex the selector string, the longer it will take jQuery to process. jQuery internally uses the browser's native DOM method to select elements. Therefore, directly using a selector to select elements is just the result of abstract encapsulation. There's nothing wrong with using selectors directly, but it's important to understand the performance of the code you're writing. Here is an example of overuse of selectors:
<SPAN class=pln>jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'body div#wrapper div#content'</SPAN><SPAN class=pun>);</SPAN>
More precise positioning does not mean that the code will run faster. The above selector can be rewritten as:
<SPAN class=pln>jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'#content'</SPAN><SPAN class=pun>);</SPAN>
Compared with the previous example, this code does the same thing, but saves a lot of performance overhead. It is worth noting that sometimes we can further improve performance by specifying the context of the selector.