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(). You can try to run the following code to learn how to count column in a table:

Eaxmple

Live Demo

<html>
  <head>
    <title>jQuery Example</title>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <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="1">-2nd column-</td>
    <td colspan="1">-3rd column-</td>
  <tr>
  </table>
</body>
</html

Updated on: 20-Jun-2020

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements