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.
Use .length not .size()
jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property.
To find out how many <a> tags there are on a page and display it in an alert dialog, do this:
window.alert($('a').length);
Click the button below to see this in action (note that if you are viewing this article in a feed reader then you need to click through to this post in a web browser for the button to work):
Note that it will match any <a> tags that are present in Javascript generated content as well, hence the high number when you click the above button because it will include all the links in the Subscribe and Share/Save buttons in the Subscribe / Share section under this post.
To just get the count of the <a> tags in a selected div, use the normal jQuery selectors in place of the 'a' above. For example, the right side navigation in this blog is #right. To get a count of the anchor tags in the right nav we would do this:
window.alert($('#right a').length);
To see this in action click the button below:
Work out if an element exists with jQuery
Finally the .length property can be used to work out if an element exists on the page or within a div etc. For example, if we wanted to take some action if there were images within the #images div, we could do this:
if($('#images img').length) { // do something } else { // do something else }
So easy, and so easy with jQuery!