How to count number of columns in a table with jQuery

To count number of columns in a table with jQuery, use the each() function with attr(). This method iterates through each cell in the first row and accounts for cells that span multiple columns using the colspan attribute.

Example

You can try to run the following code to learn how to count columns in a table −

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
    </style>
    <script>
        $(document).ready(function(){
            var num = 0;
            $('tr:nth-child(1) td').each(function () {
                if ($(this).attr('colspan')) {
                    num += +$(this).attr('colspan');
                } else {
                    num++;
                }
            });
            alert("Total Columns = " + num);
        });
    </script>
</head>
<body>
    <table>
        <tr>
            <td>1st column</td>
            <td colspan="2">2nd & 3rd columns (merged)</td>
            <td>4th column</td>
        </tr>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
            <td>Data 3</td>
            <td>Data 4</td>
        </tr>
    </table>
</body>
</html>

The output of the above code is −

Total Columns = 4

The code works by selecting all td elements in the first table row using $('tr:nth-child(1) td'). For each cell, it checks if a colspan attribute exists. If it does, the colspan value is added to the counter; otherwise, the counter is incremented by 1. This approach accurately counts the total number of logical columns even when some cells span multiple columns.

Updated on: 2026-03-13T20:45:07+05:30

882 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements