jQuery: Count Elements, Images, Classes etc
Tip by Stefan Trost | Last update on 2023-12-18 | Created on 2013-01-28
Each jQuery selector is also an array of the related elements and has the property "length". We can make use of that to determine the number of certain elements of a website.
With this method, everything is possible to count, what we can select with jQuery: the number of images, the number of headings, the number of p elements, the number of links, the number of elements with a certain ID or class, other more complicated combined constructs and much more.
First, let's look at a simple example:
var number = $('img').length; alert("The page contains " + number + " images.");
With the selector $('img'), we are selecting all images from the current page (images are marked with the "img" tag in HTML, provided that they are not embedded as a background image of an element via "background-image" or the like). After that, we display an alert showing the number of images.
More Examples
Let's look at some more examples of determining the number of elements with a certain ID or certain classes:
var num1 = $('.a').length; var num2 = $('#b').length; var num3 = $('.c.d').length;
Here, first of all, we are determining the number of elements with the class "a", then all elements with the ID "b" and finally all elements having classes "c" and "d" assigned.
You can use each jQuery selector you can imagine for this.
Check whether a certain Element exists
Even if we are not interested in the exact number of a certain element or a certain element group, but we just want to know whether one of these elements is existing on our web page, we can work with the method presented here. We just have to check whether .length is 0 or larger than 0, to know whether there are elements of this type or not.
About the Author
You can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile
Related Topics
jQuery: Does an Element exist?
Tip | 1 Comment
PHP: Remove all empty elements from string array
Tip | 0 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
Mouseover buttons using CSS without reloading
Tutorial | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
HTML: Difference between ID and CLASS
Info | 0 Comments
jQuery: Count characters from multiple input fields
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.