Several jQuery ways to find dom
This article mainly records the basic jQuery dom search methods encountered in recent development, and then compares the performance of various methods. The purpose is to hope that you can use the optimal solution when searching for dom elements in the future. The introduction in the article is very detailed. Friends who need it can refer to it. Let’s take a look together.
Preface
This problem arises due to the differences in coding habits of everyone in our front-end team, and the most important reason is the maintainability of the code. On this basis, I carefully reviewed the content related to finding dom nodes in the jQuery source code (1.11.3), although I could not understand it very deeply. . At the same time, based on the understanding of the browser console object, a series of subsequent questions and analysis were generated, and a comparative analysis of search efficiency and performance was conducted on the three most commonly used DOM search methods of jQuery.
First of all, we need to use the two methods of the console object, console.time() and console.timeEnd(), which appear in pairs. The usage of this method is to connect them The code segment executes and outputs the execution time consumed, and the string names passed in the two must be unified to take effect. For example:
console.time('Scott'); console.log('seven'); console.timeEnd('Scott'); seven Scott: 0.256ms
The correct usage is that the three places in the code segment are consistent.
Text
Next let’s discuss our commonly used jQuery search methods for DOM:
1.$(‘.parent .child'); 2.$(‘.parent').find(‘.child'); 3.$(‘.child','.parent');
Methods 1 and 3 are both search methods based on jQuery’s selector and context. , which is our most commonly used jQuery() or $(),
The details are:
jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }
Based on line 70 of jQuery (1.11.3), it is the entrance to this method and all the things he does It just creates an object of the init method on jquery.fn. Let’s take a closer look at what this object is:
init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }
Based on jQuery (1.11.3) at line 2776, the method is relatively long, I will give you an overview Let me talk about my understanding of this method: The main thing here is to judge the selector first. After the judgment is completed, search for the context. If it exists, continue to process the situation where the context exists. If not, process the situation where there is no context. Method 1 and Method 3:
1.$(‘.parent .child'); 3.$(‘.child','.parent');
They all have to enter the same judgment step, that is, the judgment process briefly explained above. The time spent after the judgments of 1 and 3 are basically the same, but the selector inside 1 It also takes time to perform sizzle related searches, and we get:
-
Method 1. $('.parent .child'); Time spent to complete the process: a;
Method 3. $('.child','.parent'); Time spent to complete the process: a; The dom node has almost been found
Method 1. $('.parent .child'); The time spent by sizzle related search selector .parent .child: b;
-
So we draw the preliminary conclusion:
Method 3. $('.child','.parent');Time spent: a;
Method 1. $('. parent .child');Time spent: a + b;
Method 3 is better than Method 1
Next let’s look at the actual Running results:
Taking Baidu pages as an example, we randomly find a set of satisfactory ranges to search for. The blogger conducted multiple tests, and the search efficiency of method 3 was uniform. It is faster than method 1, and the search speed of method 3 is basically about 3 times that of method 1, that is:
Next we add jQuery’s find method for comparison, that is For:
Method 1. $('.parent .child');
Method 2. $('.parent'). find('.child');
Method 3. $('.child','.parent');
Because we Based on the previous judgment, all three of them have to search for jQuery(), so all three of them spend a search time here. At this time, method 3 has basically been found:
-
Method 3. $('.child','.parent'); Time spent: a;
Next, method 1 is used to select the '.parent .child' selector Search, method 2 is to use jQuery's find method to search, and the specific content of find is listed here:
find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }
Based on jQuery (1.11.3) 2716 lines, here we can see that the find process is relatively simple, Compared with method 1, it is more efficient to find complex selectors (in the process of finding selectors, many situations need to be eliminated, and more time is spent on processing strings, that is, to process the selector we want to express). We conclude that method 2 is better than method 1. Let’s compare the three below:
We can see that method 1 is the slowest, and method 2 and method 3 are not the same. Comparatively, method 3 is slightly better and is basically in line with our original intention, which is:
In the process of searching DOM based on jQuery, use the jquery search method and try not to write complex selectors to express it. The DOM we want to find is extremely inefficient. On the contrary, using jquery's search method, we can try to eliminate complex selectors and greatly improve search efficiency.
Since the use of method 2 may be limited, I recommend you to use method 3, which is:
Related recommendations:
JQuery’s method of finding DOM nodes_jquery
React operates the real DOM to achieve dynamic bottom sucking
Advanced supplement of dom events in js
The above is the detailed content of Several jQuery ways to find dom. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to
