Don’t use jQuery.size() to count number of elements

Here is a small quick tip for you that "Don't use jQuery.size() to count number of elements". Well jQuery provides .size() method, which returns number of element in the object. That means that you can count the number of elements within an object. For example, if you want to count total number of div elements on the page then you can use below jQuery code, which uses size() method.

//Code Starts
$(document).ready(function(){ 
 var divCount = $("div").size();
 alert(divCount);
}?);?
//Code Ends

But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call. So the best way is,

//Code Starts
$(document).ready(function(){ 
 var divCount = $("div").length;
 alert(divCount);
}?);?
//Code Ends

Also read "jQuery Performance tips & tricks"

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...