Gulshan Prajapati
Gulshan Prajapati

Reputation: 393

why we use chaining in jQuery instead of varaible reference?

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

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

Many non-value jQuery function return a reference to the jQuery object. Obviously filters and finds 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

naivists
naivists

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

Related Questions