1

Possuo uma tabela HTML que preencho com dados que possuo em um banco de dados.

Cada tag tr da minha table representa um cliente, desconsiderando a tag tr do cabeçalho.

Gostaria de adicionar um evento de click às tags tr, como se estivessem selecionando um cliente.

Tabela HTML :

<table id="modelTable">
      <thead>
        <tr>
        <th>Id User</th>
        <th>UserEmail</th>
        <th>CodeCustomer</th>
        <th>DateCreation</th>
        <th>DateContract</th>
        <th>Condition</th>
        </tr>                          
      </thead>
      <tbody></tbody>
    </table>

Estou tentando desta forma (javaScript) :

document.getElementsByTagName("tr").addEventListener('click', function () {
      console.log("clique");
});

Error :

Uncaught TypeError: document.getElementsByTagName(...).addEventListener is not a function at HTMLAnchorElement.

Devo estar deixando algo passar, contudo já gastei algum tempo procurando, gostaria que alguém pudesse me apontar onde estou errando.

5
  • Não vai dar certo mesmo quando faz isto document.getElementsByTagName("tr") é retornando uma nodelist ou seja uma array com todas os elementos tr do documento, mesmo que só tenha uma. Vc prercisa acessar por um índice assim por exemplo [0]
    – LeAndrade
    12/09/2019 às 16:43
  • @LeAndrade Obrigado pelo comentario. Sua sugestão funcionou em partes, pois só esta funcionando para a tag tr de índice 0. Quando eu adiciono por exemplo o índice 1 aparece este erro : Uncaught TypeError: Cannot read property 'addEventListener' of undefined at HTMLAnchorElement.<anonymous>
    – Levi
    12/09/2019 às 16:49
  • Sim, pq só tem uma tr.
    – LeAndrade
    12/09/2019 às 16:50
  • @ LeAndrade Mas não teria uma forma de adicionar o evento de click às tags tr que são adicionadas a tabela (createElement("tr")) ?
    – Levi
    12/09/2019 às 16:52
  • 1
    Sim, claro, mas, aí é outro esquema, vc vai ter que fazer um for() percorrendo todo documento e acessando os índices das trs pelo for.
    – LeAndrade
    12/09/2019 às 16:53

2 Respostas 2

3

O método getElementsByTagName da Documentação de interface retorna um HTMLCollection e não um HTMLAnchorElement). Acho que isso pode te interessar Qual a diferença de NodeList para HTMLCollection?

Uma forma de contornar isso é trocar o getElementsByTagName por querySelector ou querySelectorAll e fazer um forEach() para pegar só a tr clicada

Aqui tem um exemplo:

const tr = document.querySelectorAll('tbody tr');

function teste() {
	console.log('oi');
}

tr.forEach( function (e) {
    e.addEventListener('click', teste)
})
<table id="modelTable">
    <thead style="background: silver">
        <tr>
            <th>Id User</th>
            <th>UserEmail</th>
            <th>CodeCustomer</th>
            <th>DateCreation</th>
            <th>DateContract</th>
            <th>Condition</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Id User</th>
            <th>UserEmail</th>
            <th>CodeCustomer</th>
            <th>DateCreation</th>
            <th>DateContract</th>
            <th>Condition</th>
        </tr>
        <tr>
            <th>Id User</th>
            <th>UserEmail</th>
            <th>CodeCustomer</th>
            <th>DateCreation</th>
            <th>DateContract</th>
            <th>Condition</th>
        </tr>
    </tbody>
</table>

7
  • "desconsiderando a tag tr do cabeçalho"...
    – Meu ovo
    12/09/2019 às 17:15
  • 1
    É só alterar para document.querySelectorAll('#modelTable tbody tr').
    – Meu ovo
    12/09/2019 às 17:17
  • 1
    É isso aí man, +1
    – LeAndrade
    12/09/2019 às 17:22
  • 1
    Legal Hugo, obrigado! Realmente apesar de ser muito bom, está cada vez mais raro achar jQuery por aí.
    – LeAndrade
    12/09/2019 às 17:32
  • 1
    Acho mt difícil o jQuery morrer. Vc carrega apenas 80KB de código que facilita bastante a manipulação de elementos no JS. Se vai morrer um dia, pode até ser, mas acho que ainda tá longe disso acontecer.
    – Meu ovo
    13/09/2019 às 12:35
1

$(document).ready(function(){
    $("#modelTable > tbody > tr").on('click', function() {
        console.log("clique");
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="modelTable">
  <thead>
    <tr>
    <th>Id User</th>
    <th>UserEmail</th>
    <th>CodeCustomer</th>
    <th>DateCreation</th>
    <th>DateContract</th>
    <th>Condition</th>
    </tr>                          
  </thead>
  <tbody>
    <tr>
      <td>teste</td>
      <td>teste</td>
      <td>teste</td>
      <td>teste</td>
      <td>teste</td>
    </tr>
  </tbody>
</table>;

3
  • 1
    @Levi poderia ter especificado nas tags que tbm poderiam utilizar jquery, e só para deixar registrado que este método delegate() está deprecated conforme a documentação: api.jquery.com/Delegate
    – LeAndrade
    12/09/2019 às 17:15
  • 1
    @LeAndrade obrigado pelo aviso. Correção já foi feita. 12/09/2019 às 17:18
  • 1
    Desnecessário esses >, mas.... :D
    – Meu ovo
    12/09/2019 às 17:20

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .