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?
This question is related to
javascript
jquery
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.
I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.
You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size
var parent = document.getElementById("parentId");_x000D_
var nodesSameClass = parent.getElementsByClassName("test");_x000D_
console.log(nodesSameClass.length);
_x000D_
<div id="parentId">_x000D_
<p class="prueba">hello word1</p>_x000D_
<p class="test">hello word2</p>_x000D_
<p class="test">hello word3</p>_x000D_
<p class="test">hello word4</p>_x000D_
</div>
_x000D_
$('#maindivid').find('input .inputclass').length
Simplest example:
document.getElementById("demo").innerHTML = "count: " + document.querySelectorAll('.test').length;
_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p id="demo"></p>_x000D_
<ul>_x000D_
<li class="test">Coffee</li>_x000D_
<li class="test">Milk</li>_x000D_
<li class="test">Soda</li>_x000D_
</ul>_x000D_
_x000D_
</body> _x000D_
</html>
_x000D_
Source: Stackoverflow.com