jantimon
jantimon

Reputation: 38140

jQuery size() method vs length attribute

Is there any difference between $(".selector").size() and $(".selector").length ?

Upvotes: 59

Views: 33419

Answers (10)

David Adele
David Adele

Reputation: 11

Both are okay. However, length is better being a property than size() which is a method.

Moreso size() has been deprecated from jquery 1.8 and removed as of version 3.1.

So use length as much as possible

Upvotes: 0

Sourav Basak
Sourav Basak

Reputation: 486

jQuery .size() and .length both return the number of elements in the jQuery object.

Size() and length in jQuery both returns the number of element in an object but length is faster than the size because length is a property and size is a method and length property does not have the overhead of a function call.

Upvotes: 0

Ramesh kumar
Ramesh kumar

Reputation: 548

JQuery size() is a method & length is property and property is faster than method because size() internally calls length. so better to call length directly.

Upvotes: 1

Vipul Jethva
Vipul Jethva

Reputation: 675

If you will read length property then only time required to access an object property will be needed.

However if you will call size() then first of all a function will be called, this function will read length property internally and then return that value to the caller.

You can clearly see that you are doing the same thing in both cases. But if you call the function then it will include time for calling a function + returning that value too..

Upvotes: 0

B Robster
B Robster

Reputation: 42043

Yes! There is now a very significant difference. .size() is deprecated. Always use .length instead.

Upvotes: 3

doodlemoonch
doodlemoonch

Reputation: 71

Length is much faster.

See the tutorial size vs. length.

Upvotes: 7

Jon Dean
Jon Dean

Reputation: 91

They will both give you the same result but .length is slightly faster.

See http://api.jquery.com/size/:

The .length property is a slightly faster way to get this information.

Upvotes: 9

Jaymz
Jaymz

Reputation: 6348

.size() is a Method call, which returns the length property. So you either call the method to return the property, or you retrieve the property directly.

The method (.size()) is probably the one you should be using, as it was most likely implemented to abstract away from the possibility of the length property being changed.

Upvotes: 3

Fabian
Fabian

Reputation: 13691

Length returns the same thing and is slightly faster according to the jQuery documentation.

Source: http://api.jquery.com/size/

Upvotes: 16

RoToRa
RoToRa

Reputation: 38400

No. size() returns length. By using length you only avoid one extra method call.

Upvotes: 80

Related Questions