how do i iterate through all column headers in jquery datatables?

The simplest way I know to do this is with some jQuery inside the drawCallback option:

<script type="text/javascript">

  $(document).ready(function() {

    $('#example').DataTable( {

      "drawCallback": function ( settings ) {
        $('#example thead tr th').each(function() {
          console.log( $(this).html() );
        }); 
      }

    } );

  } );

</script>

I am using the more recent drawCallback, not the older legacy fnDrawCallback (but both do work).


Just to note: In your question, you are using table.column().every( function () {...}. I can’t see how you are defining your table variable, in your example. So if my suggested approach is not suitable, perhaps you can edit your question to show the context in which you are using fnDrawCallback.


Update

If you want to hide one or more columns based on the names of the column headings, then you can take the above code and modify it as follows:

<script type="text/javascript">

  $(document).ready(function() {

    $('#example').DataTable( {

      "drawCallback": function ( settings ) {
        var tbl = $('#example').DataTable();

        var colIndex = 0;
        $('#example thead tr th').each(function() {
          var colHeading = $(this).html();
          if (colHeading === 'Office' || colHeading === 'Age') {
            tbl.columns( colIndex ).visible( false );
          }
          colIndex += 1;
        }); 
      }

    } );

  } );

</script>

In the above example, I have a table where the “Office” and “Age” columns are hidden when the table is drawn.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top