How to insert dynamic rows into HTML table, and already set a class beforehand

1

I have an HTML table and I'm creating your lines dynamically using appendChild() , I'm just not able to set className dynamically on those lines, in the third column - "VALUE".

See like this:

        var doc = document;

        function inserirLinha(id) {
            var newRow = doc.createElement('tr');
            newRow.insertCell(0).innerHTML = 'ID';
            newRow.insertCell(1).innerHTML = 'NOME';
            newRow.insertCell(2).innerHTML = 'VALOR';
            doc.getElementById(id).appendChild(newRow);
            return false;
        }
    <form onsubmit="return inserirLinha('minhaTabela')">
        <table>
            <tr>
                <tbody id="minhaTabela"></tbody>
            </tr>
        </table>
        <input type="submit" value="Adicionar" name="submit">
    </form>
    
asked by anonymous 03.06.2018 / 14:11

1 answer

3

Just assign insertCell to a variable and then define the name of the class you want by using the className

var opt = document;

function inserirLinha(id) {
  var newRow = opt.createElement('tr');
  newRow.insertCell(0).innerHTML = 'ID';
  newRow.insertCell(1).innerHTML = 'NOME';
  colunaValor = newRow.insertCell(2);
  colunaValor.innerHTML = 'VALOR';
  colunaValor.className = 'teste';
  opt.getElementById(id).appendChild(newRow);
  return false;
}
<form onsubmit="return inserirLinha('minhaTabela')">
  <table>
    <tr>
      <tbody id="minhaTabela"></tbody>
    </tr>
  </table>
  <input type="submit" value="Adicionar" name="submit">
</form>
    
03.06.2018 / 14:18