How to insert dynamic lines in HTML table, and already define a class ante-hand

Asked

Viewed 976 times

1

I have an HTML table and I am creating your lines dynamically using appendChild(), I just can’t seem to define className dynamically on these lines, in the third column - "VALUE".

See how 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>

1 answer

3


Just assign the insertCell in a variable and then set the name of the class you want using the property 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>

Browser other questions tagged

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