How to count number of columns in a table with jQuery

jQueryWeb DevelopmentFront End Technology

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
raja
Published on 31-Jul-2018 17:40:01
Advertisements