Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery count number of divs with a certain class?

Tags:

html

jquery

count

People also ask

How can I count the number of elements with same class?

To count the number of elements with same class with JavaScript, we can use the querySelectorAll method. const count = document. querySelectorAll("#main-div . specific-class").

How do I count the number of divs?

To count the elements in a div: Select the div element. Call the getElementsByTagName() method on the div , passing it an asterisk as a parameter. Access the length property on the collection.

How do I count the number of elements in jQuery?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object. where selector is the object whose length is to be calculated.

What is .each in jQuery?

The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.


You can use the jquery .length property

var numItems = $('.item').length;

For better performance you should use:

var numItems = $('div.item').length;

Since it will only look for the div elements in DOM and will be quick.

Suggestion: using size() instead of length property means one extra step in the processing since SIZE() uses length property in the function definition and returns the result.


You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/


And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp


I just created this js function using the jQuery size function http://api.jquery.com/size/

function classCount(name){
  alert($('.'+name).size())
}

It alerts out the number of times the class name occurs in the document.


can count child divs like this

let number_of_child_divs =  $('.wrapper').children('.item').length;

outout : 5