What are downside and advantage of method chaining in jQuery ?
Is it faster than re-declaring selector?
What are downside and advantage of method chaining in jQuery ?
Is it faster than re-declaring selector?
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.
Advantages of method chaining:
$(this).next().find("span.title").closest(".section").hide();
. Without chaining, you would need four different local variables where this needs none.Disadvantages of chaining:
Yes, it can be faster but not when compared with storing the jQuery object in a variable, which is just as fast.
e.g. this:
var elements = $('.myClass').find('p');
elements.next()
should be just as fast as this:
$('.myClass').find('p').next()
Most of the time it comes down to readability...sometimes method chaining makes code more readable, but if you get carried away, it can make it less readable.