Add new col on button click using javascript

Here is an example of how you can add a new column to a table on button click using JavaScript:

// Get the table and button elements
const table = document.getElementById('myTable');
const addButton = document.getElementById('addButton');

// Add an event listener to the button
addButton.addEventListener('click', addColumn);

// Function to add a new column
function addColumn() {
  // Create a new column element
  const newColumn = document.createElement('th');
  newColumn.textContent = 'New Column';

  // Add the new column to the table
  table.insertAdjacentElement('beforeend', newColumn);

  // Update the table's column count
  table.columns = table.columns + 1;
}

This code assumes that you have a table with an ID of "myTable" and a button with an ID of "addButton". When the button is clicked, the addColumn function is called, which creates a new <th> element and adds it to the table using the insertAdjacentElement method. The table.columns property is then updated to reflect the new column count.

You can also use appendChild method to add the new column to the table.

function addColumn() {
  // Create a new column element
  const newColumn = document.createElement('th');
  newColumn.textContent = 'New Column';

  // Add the new column to the table
  table.tHead.appendChild(newColumn);

  // Update the table's column count
  table.columns = table.columns + 1;
}

You can also use insertBefore method to add the new column to the table.

function addColumn() {
  // Create a new column element
  const newColumn = document.createElement('th');
  newColumn.textContent = 'New Column';

  // Add the new column to the table
  table.tHead.insertBefore(newColumn, table.tHead.children[table.columns]);

  // Update the table's column count
  table.columns = table.columns + 1;
}

You can also use a library like jQuery to make it easier to add a new column to the table.

$('#addButton').on('click', function() {
  $('#myTable th:last-child').after('<th>New Column</th>');
  $('#myTable').DataTable().columns.add();
});

This code uses the jQuery library to add a new <th> element to the table after the last existing column, and then updates the table's column count using the DataTable method.

You can also use a template engine like Handlebars to add a new column to the table.

$('#addButton').on('click', function() {
  const newColumn = Handlebars.compile('<th>{{newColumn}}</th>');
  $('#myTable th:last-child').after(newColumn({ newColumn: 'New Column' }));
  $('#myTable').DataTable().columns.add();
});

This code uses the Handlebars template engine to compile a new <th> element with the text "New Column", and then adds it to the table after the last existing column.