Chaining events and repeating the DOM

Below I have two jQuery selectors.

First, the DOM element is searched in the cached object, and then its parents are searched, then it binds the parents (table) to another dom element. (example 2)

The second (2 lines) searches through the cached item. (example 1)

$('element', table.setting.body).on('blur focus', table.focus).parents('parent').find('another element').on('click', function); // ex2 $('element', table.setting.body).on('blur focus', function); // ex 1 $('another element', table.setting.body).on('click', function); // ex 1 

Which one is faster / better?
Ex. 1, no doubt, will be faster to repeat jQuery functions, i.e. .hide().animate().show() , but when does this happen when looking for DOM elements?

enter image description here

+8
jquery
source share
3 answers

It looks like you are trying to map different descendants from table.setting.body and perform different tasks for these descendants without specifying table.setting.body twice.

You can use end () to achieve this. For example, if table.setting.body is a jQuery object, you can write:

 table.setting.body.find("element").on("blur focus", function).end() .find("another element").on("click", function); 

(If table.setting.body is a DOM element, you need to first apply $() to it.)

In the above code, the cached object is evaluated only once, it makes two calls to find() (a little faster than your calls to $() with the context argument in my experience), two calls to on() (the same as yours) and one calling end() (which only pops the item from the stack and should be pretty fast).

0
source share

In my opinion, this is a question more about speed, but rather about maintainability and good coding style.

And this is where example 1 is much better than example 2.

Avoid confusion and keep things aside. You want to attach 2 events to 2 different elements - write 2 statements. This makes your code much more structured and readable.

+1
source share

The only difference I see is the use of parents in your first approach. jQuery.parents searches for the right parent using a loop inside the dir function:

 parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, // ... dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, 

(http://code.jquery.com/jquery-1.8.2.js)

cur = elem[ dir ] means elem["parentNode"] and is repeated for all parents, because before undefined. There is no shortcut if the desired parent is specified as a link.

Depending on the length of the path between the first element you are looking for and the document root, the first approach requires more DOM operations.

Therefore, I recommend the second approach.

0
source share

All Articles