Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are downside and advantage of method chaining in jQuery? [closed]

What are downside and advantage of method chaining in jQuery ?

Is it faster than re-declaring selector?

like image 940
hd. Avatar asked Mar 06 '13 06:03

hd.


1 Answers

Most probably the advantages are,

that It makes your code short and easy to manage.It gives better performance(faster). And the chain starts from left to right. So left most will be called first and so on.

When chaining is used JQuery has to find the elements once and it will execute all the attached functions one by one.

An disadvantage of chaining can be using it unnecessarily too much then it can cause performance degrading.

eg:- Code 1:

​$(document).ready(function(){
    $('#myContent').addClass('hello');
    $('#myContent').css('color', 'blue');
    $('#myContent').fadeOut('fast');
});​

Code 2:

$(document).ready(function(){
    $('#myContent').addClass('hello')
          .css('color', 'blue')
          .fadeOut('fast');     
});​

Both these code does the same thing. and the Code 2 uses chaining and it is faster and shorter in code. And in Code 1 JQuery has to search the entire DOM to find the element and after that it executes the function on it.

like image 185
Swarne27 Avatar answered Oct 01 '22 06:10

Swarne27