Create PivotTable Header

0

I'm trying to create a dynamic array-based header that the function receives, the structure I tried, and did not work, is as follows:

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 resolve this?

    
asked by anonymous 21.10.2018 / 00:59

1 answer

2

You can do 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 was not working because of these points:

  • In header.createElement('tr') : The thead element does not have a createElement() method, you have to use the document object method and then add the tr element created in the document to the thead element; and you were not storing the reference to the tr element created, and then adding the columns to it;
  • In header_row = header.createElement('th') : Same thing as above;
  • In header_row.innerHTML(columns[i]) : You were using innerHTML as a method, but it is a property, so you should 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>
    
21.10.2018 / 02:08