Create dynamic table header

Asked

Viewed 179 times

0

I’m trying to create a dynamic header based on an array that the function receives, the structure I tried, and it didn’t work, is the following:

function createDynamicHeader(columns) {

          var table = document.querySelector('#table_teste');

          var header = table.createTHead();

          header.createElement('tr');

          for (var i = 0; i < columns.length; i++) {
              var header_row = header.createElement('th');
              header_row.innerHTML(columns[i]);
          }

      }

HTML:

<table id="table_teste" class="table table-bordered"></table>

How can I fix this?

1 answer

2


You can do it like this:

function createDynamicHeader(columns) {
  var table = document.querySelector('#table_teste');

  // Cria um elemento <thead> vazio e o adiciona à tabela:
  var header = table.createTHead();

  // Cria um elemento <tr> vazio dentro do header da tabela:
  var row = header.insertRow();

  for (var i = 0; i < columns.length; i++) {
    // Insere uma nova célula (<td>) dentro do elemento <tr>:
    var cell = row.insertCell();
    // Adiciona algum texto na nova célula:
    cell.innerHTML = columns[i];
  }
}

// Chama a função para testar.
createDynamicHeader(['Coluna TD 1', 'Coluna TD 2', 'Coluna TD 3'])
<table id="table_teste" class="table table-bordered"></table>

But your code wasn’t working because of those dots:

  • In header.createElement('tr'): The element thead has no method createElement(), you have to use the object method document and then add the element tr created in the document to the element thead; and you were not storing the reference to the element tr created, to then add the columns to it;
  • In header_row = header.createElement('th'): Same thing as the previous one;
  • In header_row.innerHTML(columns[i]): You were using innerHTML as a method, but it is a property, so you should do header_row.innerHTML = columns[i].

Follow the same solution using your original code:

function createDynamicHeader(columns) {
  var table = document.querySelector('#table_teste');

  var header = table.createTHead();

  var row = document.createElement('tr');
  header.appendChild(row);

  for (var i = 0; i < columns.length; i++) {
    var cell = document.createElement('th');
    cell.innerHTML = columns[i];
    row.appendChild(cell);
  }
}

createDynamicHeader(['Coluna TH 1', 'Coluna TH 2', 'Coluna TH 3'])
<table id="table_teste" class="table table-bordered"></table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.