How to remove the <tr> tag using Javascript

Asked

Viewed 51 times

-1

I need to include a button in my table that will remove a patient(TR), the button I include directly in HTML is removing, but the button that is added with the append does not work.

    <header>
        <div class="container">
            <h1>Aparecida Nutrição</h1>
        </div>
    </header>
    <main>
        <section class="container">
            <h2>Meus pacientes</h2>
            <table>
                <thead>
                    <tr>
                        <th>Nome</th>
                        <th>Peso(kg)</th>
                        <th>Altura(m)</th>
                        <th>Gordura Corporal(%)</th>
                        <th>IMC</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody id="tabela-pacientes" >
                    <tr class="paciente" id="primeiro-paciente">
                        <td class="info-nome">Paulo</td>
                        <td class="info-peso">100</td>
                        <td class="info-altura">5.00</td>   
                        <td class="info-gordura">10</td>
                        <td class="info-imc">0</td>
                        <td>
                            <button class="botao-remover">Remover</button>
                        </td>
                    </tr> 

                    <tr class="paciente" >
                        <td class="info-nome">João</td>
                        <td class="info-peso">80</td>
                        <td class="info-altura">1.72</td>
                        <td class="info-gordura">40</td>
                        <td class="info-imc">0</td>
                        <td><button class="botao-remover">Remover</button></td>
                    </tr>

                    <tr class="paciente" >
                        <td class="info-nome">Erica</td>
                        <td class="info-peso">54</td>
                        <td class="info-altura">1.64</td>
                        <td class="info-gordura">14</td>
                        <td class="info-imc">0</td>
                        <td><button class="botao-remover">Remover</button></td>
                    </tr>

                    <tr class="paciente">
                        <td class="info-nome">Douglas</td>
                        <td class="info-peso">85</td>
                        <td class="info-altura">1.73</td>
                        <td class="info-gordura">24</td>
                        <td class="info-imc">0</td>
                        <td><button class="botao-remover">Remover</button></td>
                    </tr>
                    <tr class="paciente" >
                        <td class="info-nome">Tatiana</td>
                        <td class="info-peso">46</td>
                        <td class="info-altura">1.55</td>
                        <td class="info-gordura">19</td>
                        <td class="info-imc">0</td>
                        <td><button class="botao-remover">Remover</button></td>
                    </tr>
                </tbody>
            </table>
        </section>

        <section class="container">
            <h2 id="titulo-form">Adicionar novo paciente</h2>
            <ul id="mensagens-erro"></ul>
            <form id="form-adiciona">
                <div>
                    <label for="nome">Nome:</label>
                    <input id="nome" name="nome" type="text" placeholder="digite o nome do seu paciente" class="campo">
                </div>
                <div class="grupo">
                    <label for="peso">Peso:</label>
                    <input id="peso" name="peso" type="text" placeholder="digite o peso do seu paciente" class="campo campo-medio">
                </div>
                <div class="grupo">
                    <label for="altura">Altura:</label>
                    <input id="altura" name="altura" type="text" placeholder="digite a altura do seu paciente" class="campo campo-medio">
                </div>
                <div class="grupo">
                    <label for="gordura">% de Gordura:</label>
                    <input id="gordura" type="text" placeholder="digite a porcentagem de gordura do seu paciente" class="campo campo-medio">
                </div>
        
                <button id="adicionar-paciente" class="botao bto-principal">Adicionar</button>
            </form>
        </section>

    </main>
    <script src="js/calcula-imc.js"></script>
    <script src="js/form.js"></script>
    <script src="js/remove-paciente.js"></script>
</body>

Javascript

var botaoAdicionar = document.querySelector("#adicionar-paciente");

botaoAdicionar.addEventListener("click", function(event){
    event.preventDefault();
    // Retorna o formulário do HTML através do ID (#form-adiciona)
    var form = document.querySelector("#form-adiciona");
    // Armazena as propriedades do form na variavel paciente
    var paciente = obtemPacienteDoFormulario(form);
    // Cria uma nova TR E TD
    var pacienteTr = criaTr(paciente);

    var erros = validaPaciente(paciente);
    
    if(erros.length > 0){
        exibirMensagensDeErro(erros);
        return;
    }
        var tabela = document.querySelector("#tabela-pacientes");

        tabela.appendChild(pacienteTr);

        form.reset();
    
});
// Obtem os dados informados no formulário ("ADICIONAR NOVO PACIENTE"), e retornar o objeto paciente com as suas propriedades
function obtemPacienteDoFormulario(form){
    var paciente = {
        nome: form.nome.value,
        peso: form.peso.value,
        altura: form.altura.value,
        gordura: form.gordura.value,
        imc: CalculaImc(form.peso.value,form.altura.value),
    }

    return paciente;
}

function criaTr(paciente){
    var pacienteTr = document.createElement("tr");
    pacienteTr.classList.add("paciente");

    var nomeTd = criaTd(paciente.nome, "info-nome");
    var pesoTd = criaTd(paciente.peso, "info-peso");
    var alturaTd = criaTd(paciente.nome, "info-altura");
    var gorduraTd = criaTd(paciente.nome, "info-gordura");
    var imcTd = criaTd(paciente.imc, "info-nome");
    var acaoTd = document.createElement("td");
    

    nomeTd.textContent = paciente.nome;
    pesoTd.textContent = paciente.peso;
    alturaTd.textContent = paciente.altura;
    gorduraTd.textContent = paciente.gordura;
    imcTd.textContent = paciente.imc;

    pacienteTr.appendChild(nomeTd);
    pacienteTr.appendChild(pesoTd);
    pacienteTr.appendChild(alturaTd);
    pacienteTr.appendChild(gorduraTd);
    pacienteTr.appendChild(imcTd);
    pacienteTr.appendChild(acaoTd);
    acaoTd.appendChild(criaTdAcao("botao-remover"))

    return pacienteTr;
}

function criaTdAcao(classe){
    var btn = document.createElement('button');
    btn.textContent = "Remover";
    btn.classList.add(classe);

    return btn;
}

function criaTd(dados,classe){ 
    var td = document.createElement("td");
    td.textContent = dados;
    td.classList.add(classe);

    return td;
}

var pacientes = document.querySelectorAll(".paciente");

pacientes.forEach(function(paciente){
    var btn = paciente.querySelector(".botao-remover");
    btn.addEventListener("click", function(){
        btn.closest("tr").remove();
    });
});
  • after making the append has a new element in the DOM, you need to associate the event click to it

  • I do not understand, the foreach should not go through all buttons with the same class?

  • and goes through the foreach after you added the new line?

  • Do not use greetings, or thanks, see [mcve]

1 answer

0


The reason the button is not working, as mentioned in the comments, is because the added button does not have a Event Listener to capture click events.

One solution would be to add the Event Listener for every button added, but there are also other ways to handle this scenario.

As you (may) know, when an event is triggered in your DOM, unless it is interrupted, it will "climb" to the root of your element tree. This means that if a click event had its button as its source, it will go up and can be captured in elements preceding that button as well.

Instead of putting one Event Listener on each button, you could put a single Event Listener in your table, and check if the event originated from a button with the class botao-remover.

const tbody = documment.getElementById('tabela-pacientes');

tbody.addEventListener('click', function(event) {
    const target = event.target;
    if (target.classList.contains('botao-remover')) {
        target.closest('tr').remove();
    }
});

This way you automate the handling of this event for the next added button as there is no need to add one Event Listener in them, since the table element is responsible for responding to these events.

Browser other questions tagged

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