Home > Web Front-end > JS Tutorial > Several jQuery ways to find dom

Several jQuery ways to find dom

小云云
Release: 2018-01-12 09:21:16
Original
2139 people have browsed it

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
Copy after login

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');
Copy after login

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 );
}
Copy after login

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 );
 }
Copy after login

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');
Copy after login

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;
 }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template