Count the number of rows in a SharePoint table using jQuery

Ever wanted to count the number of rows in an HTML table automatically? I once had to do an inventory of a client’s file share and used a directory printing utility that gave me the option of displaying the directory listings as an HTML table. The file share had over 12,000 files and 1,500 folders, and I needed to know how many files were in each folder. Finding out how many files are in a Windows folder is not difficult. All you need to do is open a folder in Windows Explorer and depending on your version of Windows you will find the file count displayed in the Windows Explorer status bar at the bottom (See Fig. 1).

Fig. 1

Because I have better things to do with my time than open fifteen hundred folders in succession and read a file count, I wrote a little bit of JavaScript/jQuery code that would do the work for me, and this is what I will be sharing with you today. The directory printing utility produced an HTML table with <th> table headers setting off each directory as shown in Fig. 2:

Fig. 2

The HTML code that generates the above table is shown below:

File Share Inventory

\\File Share
Document.txt 0
Document – Copy.txt 0
Document – Copy (2).txt 0
Document – Copy (3).txt 0
Document – Copy (4).txt 0
Document – Copy (5).txt 0
Document – Copy (6).txt 0
Document – Copy (7).txt 0
\\File Share\Sub1
0
\\File Share\Sub1\SubSub1
Document.txt
0
Document – Copy.txt 0
Document – Copy (2).txt 0
\\File Share\Sub1\SubSub2
Document.txt
0
\\File Share\Sub1\SubSub3
Document.txt
0
Document – Copy.txt 0
Document – Copy (2).txt 0
Document – Copy (3).txt 0
\\File Share\Sub2\
Document.txt
0
Document – Copy.txt 0
Document – Copy (2).txt 0
Document – Copy (3).txt 0
Document – Copy (4).txt 0
Document – Copy (5).txt 0

Using jQuery, I created a function that iterates through all table rows and checks to see if it is a header row and if not increments a counter variable. When it encounters the next row header, it resets the counter to 0, writes the file count to a cell in the corresponding header row, and starts counting all over.

In developing this solution, the tricky part for me was to realize that because the header rows precede the countable file rows, it was better to push the counts to an array and write the file counts only after they had all been computed. Happy coding!

July 2, 2013