22 Votes

jQuery: Count Elements, Images, Classes etc

Tip by Progger99 | 28.01.2013 at 21:47

Each jQuery selector is 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, everything is possible, what we can select with jQuery: the number of images, the number of elements with a certain class, other more complicated constructs and even 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 page (images are marked with "img" in HTML). After that, we display an alert showing the number of images.

More Examples

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.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

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.