Reputation: 393
i just want know what is the methodology behind chaining system in jQuery ? why we use chaining system instead of JavaScript variable ref. for example way 1 :
$('myDiv').removeClass('off').addClass('on');
I can also like this also without chaining way 2:
var a = $('myDiv');
a.removeClass('off');
a.addClass('on');
What is the difference between way1 and way2? I have tried both and both are working.
Upvotes: 0
Views: 51
Reputation: 93571
Many non-value jQuery function return a reference to the jQuery object. Obviously filter
s and find
s etc change the set returned.
The difference is an extra local variable and slightly shorter code. Use with caution as not all jQuery methods return the same set.
Upvotes: 1
Reputation: 33511
All jQuery manipulations return a reference to the modified object. Hence, chaining is simply reusing the results of previous command. Using chaining, you can write effective "one-liners", but for longer algorithms I prefer variable references.
Upvotes: 2