Null return of a JS object in rails

0

I have the following code:

<p id="notice"><%= notice %></p>

<h1>Produtos</h1>

<table class="table table-hover custom" id="tabelaProduto">
  <thead>
    <tr>
      <th>id</th>
      <th>Nome</th>
      <th>Preco</th>
      <th>Descricao</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @produtos.each do |produto| %>
      <tr>
        <td><%= produto.id %></td>
        <td><%= produto.nome %></td>
        <td><%= produto.preco %></td>
        <td data-jtable><%= produto.descricao %></td>
        <td><%= link_to 'Show', produto %></td>
        <td><%= link_to 'Edit', edit_produto_path(produto) %></td>
        <td><%= link_to 'Destroy', produto, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>
<input type="button" id="botaosomar" value="OK" onclick="vamosSomar()" />

<br>

<%= link_to 'New Produto', new_produto_path %>

and the javascript of this view contained in app / assets / javascripts:

var tabela = document.getElementById("tabelaProduto"); console.log(tabela.firstElementChild);

I do not know why rays are returning null in this object: \

    
asked by anonymous 29.05.2017 / 20:34

1 answer

0

I discovered the reason ... it was what I suspected: JS was being loaded before rendering HTML, hence the ID of the table I was using as a parameter to assign it to a variable, it did not "exist" in the act of that assignment.

I reformatted the code as follows:

$(document).ready(function(){
    var tabela = document.getElementById("tabelaProduto");
    console.log(tabela.firstElementChild);
});

It worked! Thank you all for the attention. The doubt of one may be the doubt of another.

    
29.05.2017 / 20:56