61

Considering something like this;

<div class="wrapper">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

How would I, using jQuery (or plain JS, if it's shorter - but I doubt it) count the number of divs with the "item" class? In this example, the function should return 5, as there are 5 divs with the item class.

Thanks!

8 Answers8

145

You can use the jquery .length property

var numItems = $('.item').length;
Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
  • 8
    ...I think it should be $('div.item') to count divs with that class (and not include any other kind of element with the .item class). – jjmontes Sep 13 '11 at 15:38
  • Thanks, this is what I needed! I'll accept your answer as soon as the time limit is over! –  Sep 13 '11 at 15:43
  • 3
    @jjmontes that's true. Of course you can use any selector.. but it depends on how specifc the OP wants to get. For example `$('div.wrapper div.item')` would be even closer. – Brian Glaz Sep 13 '11 at 15:46
  • After i get the **length**, how to set an array for every div with that class ?, for example i want to input text with `.html()` in first or second div item. – M. Pancadewa Jun 07 '18 at 17:22
21

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.

Ghazanfar Mir
  • 3,493
  • 2
  • 26
  • 42
  • I'd be interested to know what the difference in time/performance in using `div.item` instead of `.item` would be, of course this would be dependent on how big the document is but generally speaking I'm curious to know if it makes a major difference – haakym Oct 28 '14 at 16:43
14

You can use jQuery.children property.

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

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Nikhil salwe
  • 355
  • 2
  • 13
3

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

crazysj
  • 405
  • 3
  • 8
Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32
2

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.

Vlad
  • 691
  • 8
  • 13
0
<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            .test {
                background: #ff4040;
                color: #fff;
                display: block;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div class="test"> one </div>
        <div class="test"> two </div>
        <div class="test"> three </div>
        <div class="test"> four </div>
        <div class="test"> five </div>
        <div class="test"> six </div>
        <div class="test"> seven </div>
        <div class="test"> eight </div>
        <div class="test"> nine </div>
        <div class="test"> ten </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function () {
            //get total length by class
            var numItems = $('.test').length;
            //get last three count
            var numItems3=numItems-3;         


            var i = 0;
            $('.test').each(function(){
                i++;
                if(i>numItems3)
                {

                    $(this).attr("class","");
                }
            })
        });
    </script>
    </body>
    </html>
  • You have to get total number of class, and then if you can get last 3 element remove so get total - 3 then using each loop and condition of last last 3 record remove class. – Pratik Shah Jan 09 '19 at 08:59
0

can count child divs like this

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

outout : 5

user889030
  • 4,353
  • 3
  • 48
  • 51
0

I was looking to count for table tr elements but in my case I was needed count should be updated in real time. Here is my solution to get tr count real time.

Jquery:

$(document).ready(function() {
   // Get initial number of rows
   var rowCount = $('#myTable tr').length;
   $('#rowCount').text(`Total rows: ${rowCount}`);

   // Handle rows being added
   $('#myTable').on('DOMNodeInserted', function() {
      rowCount = $('#myTable tr').length;
      $('#rowCount').text(`Total rows: ${rowCount}`);
   });

   // Handle rows being removed
   $('#myTable').on('DOMNodeRemoved', function() {
      rowCount = $('#myTable tr').length;
      $('#rowCount').text(`Total rows: ${rowCount}`);
   });
});

This code listens for the DOMNodeInserted and DOMNodeRemoved events on the #myTable element. When those events fire (i.e. when rows are added or removed), the code updates the rowCount variable and displays the updated count in the #rowCount element.

Liakat Hossain
  • 1,288
  • 1
  • 13
  • 24