Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count divs with a certain class

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..

like image 378
wesbos Avatar asked Dec 14 '09 07:12

wesbos


People also ask

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

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.

How do I count the number of divs inside a div?

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.

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.

How do I get the number of elements in JavaScript?

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.


3 Answers

It’s either $('.user').length (length property of Array) or $('.user').size() (size method of jQuery).

like image 150
Gumbo Avatar answered Oct 15 '22 11:10

Gumbo


Length is a property not a function. Size is a function.

like image 31
Yuriy Faktorovich Avatar answered Oct 15 '22 12:10

Yuriy Faktorovich


$(".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() );
});
like image 41
www Avatar answered Oct 15 '22 13:10

www