jquery1

Count Number of Elements With Jquery

There may be times when you need to work out how many times a particular element appears on a page or within a section with Javascript and this is easy to do with jQuery using the length property. Using the method in this post you can also work out if an element exists on the page with jQuery.

What is correct way to count number of elements using jQuery? It can be done using .length and size() method but here is a tip “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.

$(document).ready(function(){
  var divCount = $("<strong>div</strong>").size();
  alert(divCount);
});

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,

$(document).ready(function(){
  var divCount = $("<strong>div</strong>").length;
  alert(divCount);
});

Related Posts


Leave a Reply

Your email address will not be published. Required fields are marked *


*