Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a main div in my page with a specific id. Now some input elements of the same class are present in this div. So how can I count the number of these elements of same class in this div using jQuery?

like image 748
manishjangir Avatar asked Mar 13 '12 09:03

manishjangir


People also ask

How do you get all elements with the same class?

We can get text from multiple elements with the same class in Selenium webdriver. We have to use find_elements_by_xpath(), find_elements_by_class_name() or find_elements_by_css_selector() method which returns a list of all matching elements.

Can two elements have same class?

Different Elements Can Share Same Class.

How do I count elements in HTML?

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


2 Answers

With jQuery you can use

$('#main-div .specific-class').length 

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length; 
like image 63
Fabrizio Calderan Avatar answered Oct 07 '22 20:10

Fabrizio Calderan


document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

like image 35
Sheshank S. Avatar answered Oct 07 '22 19:10

Sheshank S.