Seems pretty simple but I can't get it to work.
I have two divs with the class 'user'. I want to output "you have 2 divs".
<script type="text/javascript">
$(document).ready(function() {
function divcount() {
var mycount = $('.user').length();
document.write(mycount)
}
});
</script>
I'm sure I'm missing something simple..
To count the number of elements with a specific class: Use the querySelectorAll() method to get a collection of the matching elements. Access the length property on the collection. The length property will return the number of matching elements.
To count all elements inside a div elements, we use find() method and length property. The find() method is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree.
To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.
js | count() Function. The count() function is used to count the number of collections in the element. In JavaScript, the array is first converted to a collection and then the function is applied to the collection. Return Value: Returns the count of the element in that collection.
It’s either $('.user').length
(length
property of Array) or $('.user').size()
(size
method of jQuery).
Length is a property not a function. Size is a function.
$(".user").length // use the length property
$(".user").size() // use the size method
notice that the code must be include in the $(function(){...}) block; like:
$(function(){
alert( $(".user").length );
alert( $(".user").size() );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With