Delete table row through an ID

Asked

Viewed 76 times

0

In my table the rows are entered through Javascript with an ID that is the same ID filled in the form, and these lines include a recycle bin icon that I captured as let botaoExcluir = document.querySelector(".material-icons")

My question is this: can I identify the line ID where the icon was clicked and delete the line in question? also if they know another way to do that I’m also all ears.

inserir a descrição da imagem aqui

Follow HTML, CSS and JS code for testing

let botaoInserirPessoa = document.querySelector("#inserirPessoa");
let tabela = document.querySelector("#cadastrosPessoa")

let campoId = document.querySelector("#id")
let campoNome = document.querySelector("#nome")
let campoCpf = document.querySelector("#cpf")
let campoRg =document.querySelector("#rg")
let campoNascimento = document.querySelector("#dataNascimento")
let campoSexo = document.querySelector("#sexo")

let botaoExcluir = document.querySelector(".material-icons")

let bancoDeCadastros = [
    {
      "id": 1,
      "nome": "Francisca Julia da Costa",
      "cpf": "457.696.936-65",
      "rg": "47.360.897-2",
      "data_nasc": "23/03/1944",
      "sexo": "Feminino"
    },
    {
      "id": 2,
      "nome": "Noah Felipe Silva",
      "cpf": "956.531.431-70",
      "rg": "40.974.782-8",
      "data_nasc": "11/07/1964",
      "sexo": "Masculino"
    },
    {
      "id": 3,
      "nome": "Alícia Rosângela Melo",
      "cpf": "066.291.353-18",
      "rg": "36.214.141-1",
      "data_nasc": "18/02/1978",
      "sexo": "Feminino"
    },
    {
      "id": 4,
      "nome": "Cristiane Renata Ana das Neves",
      "cpf": "946.074.401-08",
      "rg": "32.301.736-8",
      "data_nasc": "10/05/1966",
      "sexo": "Feminino"
    },
    {
      "id": 5,
      "nome": "Priscila Benedita Vanessa Ferreira",
      "cpf": "888.282.394-68",
      "rg": "44.524.670-4",
      "data_nasc": "15/11/1966",
      "sexo": "Feminino"
    },
    {
      "id": 6,
      "nome": "Bianca Carolina Nunes",
      "cpf": "484.323.140-13",
      "rg": "44.466.563-8",
      "data_nasc": "16/03/1948",
      "sexo": "Feminino"
    },
    {
      "id": 7,
      "nome": "Yuri Vicente Manuel Silveira",
      "cpf": "250.111.093-56",
      "rg": "18.597.361-9",
      "data_nasc": "05/09/1974",
      "sexo": "Masculino"
    },
    {
      "id": 8,
      "nome": "Melissa Alessandra Barros",
      "cpf": "446.675.916-25",
      "rg": "25.598.673-7",
      "data_nasc": "13/01/2000",
      "sexo": "Feminino"
    },
    {
      "id": 9,
      "nome": "Márcia Daniela Lara da Cruz",
      "cpf": "932.803.826-02",
      "rg": "40.653.176-6",
      "data_nasc": "04/06/1986",
      "sexo": "Feminino"
    },
    {
      "id": 10,
      "nome": "Filipe Anderson Rafael Assis",
      "cpf": "704.869.005-41",
      "rg": "39.383.334-3",
      "data_nasc": "19/11/1995",
      "sexo": "Masculino"
    },
    {
      "id": 11,
      "nome": "Luís Vinicius Sebastião Jesus",
      "cpf": "035.960.588-56",
      "rg": "29.915.692-8",
      "data_nasc": "23/04/1965",
      "sexo": "Masculino"
    },
    {
      "id": 12,
      "nome": "Cecília Caroline Nascimento",
      "cpf": "034.396.672-78",
      "rg": "48.673.066-9",
      "data_nasc": "04/02/1951",
      "sexo": "Feminino"
    },
    {
      "id": 13,
      "nome": "Raimunda Sandra Ferreira",
      "cpf": "757.187.891-85",
      "rg": "21.189.806-5",
      "data_nasc": "17/11/1974",
      "sexo": "Feminino"
    },
    {
      "id": 14,
      "nome": "Andreia Isabelly Juliana Melo",
      "cpf": "736.348.985-85",
      "rg": "24.677.018-1",
      "data_nasc": "11/10/1963",
      "sexo": "Feminino"
    },
    {
      "id": 15,
      "nome": "Nicolas Bernardo Moura",
      "cpf": "061.370.865-26",
      "rg": "16.302.343-8",
      "data_nasc": "08/06/1989",
      "sexo": "Masculino"
    },
    {
      "id": 16,
      "nome": "Diego Benjamin Tiago da Luz",
      "cpf": "991.152.443-42",
      "rg": "38.315.100-4",
      "data_nasc": "04/06/1990",
      "sexo": "Masculino"
    },
    {
      "id": 17,
      "nome": "Marlene Emanuelly Yasmin Cavalcanti",
      "cpf": "781.233.625-52",
      "rg": "21.068.742-3",
      "data_nasc": "15/10/1961",
      "sexo": "Feminino"
    },
    {
      "id": 18,
      "nome": "Vanessa Isabela da Luz",
      "cpf": "872.138.490-85",
      "rg": "44.289.193-3",
      "data_nasc": "05/09/1982",
      "sexo": "Feminino"
    },
    {
      "id": 19,
      "nome": "Camila Flávia Vera Mendes",
      "cpf": "790.524.518-77",
      "rg": "40.847.994-2",
      "data_nasc": "01/07/1952",
      "sexo": "Feminino"
    },
    {
      "id": 20,
      "nome": "Luana Lívia Lara Campos",
      "cpf": "532.901.056-01",
      "rg": "14.732.946-2",
      "data_nasc": "19/08/1981",
      "sexo": "Feminino"
    },
    {
      "id": 21,
      "nome": "Josefa Nina Galvão",
      "cpf": "379.743.833-80",
      "rg": "13.878.690-2",
      "data_nasc": "27/01/1943",
      "sexo": "Feminino"
    },
    {
      "id": 22,
      "nome": "Natália Isabelly Silvana da Paz",
      "cpf": "454.172.867-29",
      "rg": "22.986.096-5",
      "data_nasc": "17/09/1980",
      "sexo": "Feminino"
    },
    {
      "id": 23,
      "nome": "Amanda Sebastiana Vieira",
      "cpf": "703.941.038-90",
      "rg": "50.251.196-5",
      "data_nasc": "08/06/1960",
      "sexo": "Feminino"
    },
    {
      "id": 24,
      "nome": "Noah Pedro Alves",
      "cpf": "074.733.106-58",
      "rg": "32.110.015-3",
      "data_nasc": "14/08/1992",
      "sexo": "Masculino"
    },
    {
      "id": 25,
      "nome": "Giovana Camila da Conceição",
      "cpf": "418.746.840-49",
      "rg": "35.520.215-3",
      "data_nasc": "25/06/1947",
      "sexo": "Feminino"
    },
    {
      "id": 26,
      "nome": "Pietro Joaquim Emanuel Gonçalves",
      "cpf": "003.502.230-25",
      "rg": "12.099.068-4",
      "data_nasc": "21/04/1999",
      "sexo": "Masculino"
    },
    {
      "id": 27,
      "nome": "Tereza Kamilly Mariana Porto",
      "cpf": "050.946.705-90",
      "rg": "39.830.941-3",
      "data_nasc": "16/06/1959",
      "sexo": "Feminino"
    },
    {
      "id": 28,
      "nome": "Caroline Emanuelly Lívia Moreira",
      "cpf": "673.831.546-57",
      "rg": "24.561.727-9",
      "data_nasc": "09/04/1948",
      "sexo": "Feminino"
    },
    {
      "id": 29,
      "nome": "Gabriel Ricardo da Paz",
      "cpf": "829.270.172-98",
      "rg": "30.407.114-6",
      "data_nasc": "24/03/1980",
      "sexo": "Masculino"
    },
    {
      "id": 30,
      "nome": "Giovanni Igor Augusto Pires",
      "cpf": "584.880.490-72",
      "rg": "33.874.271-2",
      "data_nasc": "24/08/1946",
      "sexo": "Masculino"
    }
  ]

let renderCadastros = banco =>{
    
    for (let i=0; i<bancoDeCadastros.length; i++){    
        
        let novaTabela = `<tr id="${banco[i].id}">  
                            <td>${banco[i].id}</td>
                            <td>${banco[i].nome}</td>
                            <td>${banco[i].cpf}</td>
                            <td>${banco[i].rg}</td>
                            <td>${banco[i].data_nasc}</td>
                            <td>${banco[i].sexo}</td>
                            <td class="material-icons">delete_forever</td>
                        </tr>`
                        
        tabela.innerHTML += novaTabela
    }
}

botaoInserirPessoa.addEventListener("click", ()=>{
    
    let id = campoId.value
    let nome = campoNome.value
    let cpf = campoCpf.value
    let rg = campoRg.value
    let nascimento = campoNascimento.value
    let sexo = campoSexo.value

    let novaTabela = `<tr id="${id}">  
                        <td>${id}</td>
                        <td>${nome}</td>
                        <td>${cpf}</td>
                        <td>${rg}</td>
                        <td>${nascimento}</td>
                        <td>${sexo}</td>
                        <td class="material-icons">delete_forever</td>
                    </tr>`          
    
    //Limpa os campos do formulário                
    campoId.value = ""
    campoNome.value = ""
    campoCpf.value = ""
    campoRg.value = ""
    campoNascimento.value = "" 
    campoSexo.value = ""
    
    //Inclui os novos dados na tabela
    tabela.innerHTML += novaTabela

    //Atualiza o banco de cadatros
    let novoCadastro = {
        "id": id,
        "nome": nome,
        "cpf": cpf,
        "rg": rg,
        "data_nasc": nascimento,
        "sexo": sexo
    }

    bancoDeCadastros.push(novoCadastro)
})

renderCadastros(bancoDeCadastros)
/*Root*/
*{
    font-size: 16px;
    margin: 0;
    padding: 0;
    font-family: Roboto;
    color: rgb(51, 51, 51);
}

/*Container principal*/
#container{
    text-align: center;
    align-items: center;
    margin: 15px;
}

/*Campos do formulário*/
#inserirDados div, input, button{
    margin: 5px 0 5px 0;
    padding: 3px;
}

#inserirDados input{
    width: 120px;
}

#inserirDados button{
    width: 60px;
    border: 0;
    border-radius: 8px;
    
    color: rgb(248, 248, 248);
    background-color: rgb(38, 98, 230);

    transition: .3s;
}
#inserirDados button:hover {
    cursor: pointer;
    background-color: rgb(42, 89, 190);
    transition: .3s;
}

/*Tabela*/
#cadastrosPessoa{
    margin: auto;
    border-collapse: collapse;
    text-align: left;
}

#cadastrosPessoa th{
    border: 0;
}

#cadastrosPessoa td{
    border: 1px solid  rgb(77, 226, 122);
    font-weight: normal;

    padding: 3px;
}

#cadastrosPessoa .material-icons{
    cursor:pointer;
    
    transition: .3s;
}

#cadastrosPessoa .material-icons:hover{
    
    color: tomato;
    transition: .3s;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Listagem de pessoas</title>
</head>
<body>
    
    <div id="container">
        <div id="inserirDados">
            <h1>Adicionar colaborador</h1>
            <input type="text" name="id" id="id" placeholder="ID">
            <input type="text" name="nome" id="nome" placeholder="Nome">
            <input type="text" name="cpf" id="cpf" placeholder="CPF">
            <input type="text" name="rg" id="rg" placeholder="RG">
            <input type="text" name="dataNascimento" id="dataNascimento" placeholder="Nascimento">
            <input type="text" name="sexo" id="sexo" placeholder="Sexo">
            <br>
            <button id="inserirPessoa">OK</button>
        </div>
    </div>
        
    <table id="cadastrosPessoa">
        <tr>
            <th>ID</th>
            <th>Nome</th>
            <th>CPF</th>
            <th>RG</th>
            <th>Nascimento</th>
            <th>Sexo</th>
            <th></th>
        </tr>
    </table>
        
</body>

<script src="/scripts.js"></script>

<link rel="stylesheet" href="/main.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">

</html>

]2]2

  • I think the logic there would be to click on the delete: remove the database record and recreate the table.

2 answers

2


Alternative to another answer, you can do it this way, since the id of his <tr> and unique, can associate the same id of his <tr> an attribute that we can call data-id in his .material-icons, in the loop for where you create the <tr>:

let renderCadastros = (banco) => {
  for (let i = 0; i < bancoDeCadastros.length; i++) {
    let novaTabela = `<tr id="${banco[i].id}">
                        <td>${banco[i].id}</td>
                        <td>${banco[i].nome}</td>
                        <td>${banco[i].cpf}</td>
                        <td>${banco[i].rg}</td>
                        <td>${banco[i].data_nasc}</td>
                        <td>${banco[i].sexo}</td>
                        <td class="material-icons" data-id="${banco[i].id}">delete_forever</td>
                    </tr>`;
                        // adicionando data-id="${banco[i].id} para o elemento

    tabela.innerHTML += novaTabela;
  }
};

Now let’s rewrite the:

let botaoExcluir = document.querySelector(".material-icons")

for:

let botaoExcluir = document.querySelectorAll('.material-icons');

To select all elements that will delete and add an event from click for each of them. For this, we will make a loop forEach, for querySelectorAll returns an array, and add the addEventListener for each one:

botaoExcluir.forEach((el) => {
  el.addEventListener('click', () => {
    ...
  });
});

And now, let’s capture the data-id of each of those elements to data-id, we will remove the <tr> of the document, since data-id and equal to id of <tr>:

botaoExcluir.forEach((el) => {
  el.addEventListener('click', () => {
    const idLinha = el.getAttribute('data-id'); // pegamos o valor 'data-id'

    console.log(document.getElementById(`${idLinha}`)); // neste log vai mostrar o
                                                        // <tr> com id igual a 'data-id'

    document.getElementById(`${idLinha}`).remove(); // selecionamos o elemento com valor
                                                    // do id igual ao valor de data-id
                                                    // e o removeremos do documento.
  });
});

For everything to work properly, all the above code must be added after the run renderCadastros(bancoDeCadastros), because the elements have to be rendered in the document before they are captured. I will create a function called addEventToMaterialIcons which will contain all the logic and we will run it next:

renderCadastros(bancoDeCadastros);

function addEventToMaterialIcons() {
  let botaoExcluir = document.querySelectorAll('.material-icons');

  botaoExcluir.forEach((el) => {
    el.addEventListener('click', () => {
      const idLinha = el.getAttribute('data-id');

      console.log(document.getElementById(`${idLinha}`));
      document.getElementById(`${idLinha}`).remove();
    });
  });
}

Now to solve the problem you mentioned in the comment, let’s change a little the logic that creates a new row in the table. Let’s just add the call to the function addEventToMaterialIcons inside, to avoid code repetition:

botaoInserirPessoa.addEventListener('click', () => {
  let id = campoId.value;
  let nome = campoNome.value;
  let cpf = campoCpf.value;
  let rg = campoRg.value;
  let nascimento = campoNascimento.value;
  let sexo = campoSexo.value;

  let novaTabela = `<tr id="${id}">
                <td>${id}</td>
                <td>${nome}</td>
                <td>${cpf}</td>
                <td>${rg}</td>
                <td>${nascimento}</td>
                <td>${sexo}</td>
                <td class="material-icons" data-id="${id}">delete_forever</td>
            </tr>`;

  //Limpa os campos do formulário
  campoId.value = '';
  campoNome.value = '';
  campoCpf.value = '';
  campoRg.value = '';
  campoNascimento.value = '';
  campoSexo.value = '';

  //Inclui os novos dados na tabela
  tabela.innerHTML += novaTabela;

  //Atualiza o banco de cadatros
  let novoCadastro = {
    id: id,
    nome: nome,
    cpf: cpf,
    rg: rg,
    data_nasc: nascimento,
    sexo: sexo,
  };

  addEventToMaterialIcons();

  bancoDeCadastros.push(novoCadastro);
});

As a new element has been added, we will assign a click event to it, so we invoke addEventToMaterialIcons.

Final code:

  let botaoInserirPessoa = document.querySelector('#inserirPessoa');
  let tabela = document.querySelector('#cadastrosPessoa');

  let campoId = document.querySelector('#id');
  let campoNome = document.querySelector('#nome');
  let campoCpf = document.querySelector('#cpf');
  let campoRg = document.querySelector('#rg');
  let campoNascimento = document.querySelector('#dataNascimento');
  let campoSexo = document.querySelector('#sexo');

  let bancoDeCadastros = [
    {
      id: 1,
      nome: 'Francisca Julia da Costa',
      cpf: '457.696.936-65',
      rg: '47.360.897-2',
      data_nasc: '23/03/1944',
      sexo: 'Feminino',
    },
    {
      id: 2,
      nome: 'Noah Felipe Silva',
      cpf: '956.531.431-70',
      rg: '40.974.782-8',
      data_nasc: '11/07/1964',
      sexo: 'Masculino',
    },
    {
      id: 3,
      nome: 'Alícia Rosângela Melo',
      cpf: '066.291.353-18',
      rg: '36.214.141-1',
      data_nasc: '18/02/1978',
      sexo: 'Feminino',
    },
    {
      id: 4,
      nome: 'Cristiane Renata Ana das Neves',
      cpf: '946.074.401-08',
      rg: '32.301.736-8',
      data_nasc: '10/05/1966',
      sexo: 'Feminino',
    },
    {
      id: 5,
      nome: 'Priscila Benedita Vanessa Ferreira',
      cpf: '888.282.394-68',
      rg: '44.524.670-4',
      data_nasc: '15/11/1966',
      sexo: 'Feminino',
    },
    {
      id: 6,
      nome: 'Bianca Carolina Nunes',
      cpf: '484.323.140-13',
      rg: '44.466.563-8',
      data_nasc: '16/03/1948',
      sexo: 'Feminino',
    },
    {
      id: 7,
      nome: 'Yuri Vicente Manuel Silveira',
      cpf: '250.111.093-56',
      rg: '18.597.361-9',
      data_nasc: '05/09/1974',
      sexo: 'Masculino',
    },
    {
      id: 8,
      nome: 'Melissa Alessandra Barros',
      cpf: '446.675.916-25',
      rg: '25.598.673-7',
      data_nasc: '13/01/2000',
      sexo: 'Feminino',
    },
    {
      id: 9,
      nome: 'Márcia Daniela Lara da Cruz',
      cpf: '932.803.826-02',
      rg: '40.653.176-6',
      data_nasc: '04/06/1986',
      sexo: 'Feminino',
    },
    {
      id: 10,
      nome: 'Filipe Anderson Rafael Assis',
      cpf: '704.869.005-41',
      rg: '39.383.334-3',
      data_nasc: '19/11/1995',
      sexo: 'Masculino',
    },
    {
      id: 11,
      nome: 'Luís Vinicius Sebastião Jesus',
      cpf: '035.960.588-56',
      rg: '29.915.692-8',
      data_nasc: '23/04/1965',
      sexo: 'Masculino',
    },
    {
      id: 12,
      nome: 'Cecília Caroline Nascimento',
      cpf: '034.396.672-78',
      rg: '48.673.066-9',
      data_nasc: '04/02/1951',
      sexo: 'Feminino',
    },
    {
      id: 13,
      nome: 'Raimunda Sandra Ferreira',
      cpf: '757.187.891-85',
      rg: '21.189.806-5',
      data_nasc: '17/11/1974',
      sexo: 'Feminino',
    },
    {
      id: 14,
      nome: 'Andreia Isabelly Juliana Melo',
      cpf: '736.348.985-85',
      rg: '24.677.018-1',
      data_nasc: '11/10/1963',
      sexo: 'Feminino',
    },
    {
      id: 15,
      nome: 'Nicolas Bernardo Moura',
      cpf: '061.370.865-26',
      rg: '16.302.343-8',
      data_nasc: '08/06/1989',
      sexo: 'Masculino',
    },
    {
      id: 16,
      nome: 'Diego Benjamin Tiago da Luz',
      cpf: '991.152.443-42',
      rg: '38.315.100-4',
      data_nasc: '04/06/1990',
      sexo: 'Masculino',
    },
    {
      id: 17,
      nome: 'Marlene Emanuelly Yasmin Cavalcanti',
      cpf: '781.233.625-52',
      rg: '21.068.742-3',
      data_nasc: '15/10/1961',
      sexo: 'Feminino',
    },
    {
      id: 18,
      nome: 'Vanessa Isabela da Luz',
      cpf: '872.138.490-85',
      rg: '44.289.193-3',
      data_nasc: '05/09/1982',
      sexo: 'Feminino',
    },
    {
      id: 19,
      nome: 'Camila Flávia Vera Mendes',
      cpf: '790.524.518-77',
      rg: '40.847.994-2',
      data_nasc: '01/07/1952',
      sexo: 'Feminino',
    },
    {
      id: 20,
      nome: 'Luana Lívia Lara Campos',
      cpf: '532.901.056-01',
      rg: '14.732.946-2',
      data_nasc: '19/08/1981',
      sexo: 'Feminino',
    },
    {
      id: 21,
      nome: 'Josefa Nina Galvão',
      cpf: '379.743.833-80',
      rg: '13.878.690-2',
      data_nasc: '27/01/1943',
      sexo: 'Feminino',
    },
    {
      id: 22,
      nome: 'Natália Isabelly Silvana da Paz',
      cpf: '454.172.867-29',
      rg: '22.986.096-5',
      data_nasc: '17/09/1980',
      sexo: 'Feminino',
    },
    {
      id: 23,
      nome: 'Amanda Sebastiana Vieira',
      cpf: '703.941.038-90',
      rg: '50.251.196-5',
      data_nasc: '08/06/1960',
      sexo: 'Feminino',
    },
    {
      id: 24,
      nome: 'Noah Pedro Alves',
      cpf: '074.733.106-58',
      rg: '32.110.015-3',
      data_nasc: '14/08/1992',
      sexo: 'Masculino',
    },
    {
      id: 25,
      nome: 'Giovana Camila da Conceição',
      cpf: '418.746.840-49',
      rg: '35.520.215-3',
      data_nasc: '25/06/1947',
      sexo: 'Feminino',
    },
    {
      id: 26,
      nome: 'Pietro Joaquim Emanuel Gonçalves',
      cpf: '003.502.230-25',
      rg: '12.099.068-4',
      data_nasc: '21/04/1999',
      sexo: 'Masculino',
    },
    {
      id: 27,
      nome: 'Tereza Kamilly Mariana Porto',
      cpf: '050.946.705-90',
      rg: '39.830.941-3',
      data_nasc: '16/06/1959',
      sexo: 'Feminino',
    },
    {
      id: 28,
      nome: 'Caroline Emanuelly Lívia Moreira',
      cpf: '673.831.546-57',
      rg: '24.561.727-9',
      data_nasc: '09/04/1948',
      sexo: 'Feminino',
    },
    {
      id: 29,
      nome: 'Gabriel Ricardo da Paz',
      cpf: '829.270.172-98',
      rg: '30.407.114-6',
      data_nasc: '24/03/1980',
      sexo: 'Masculino',
    },
    {
      id: 30,
      nome: 'Giovanni Igor Augusto Pires',
      cpf: '584.880.490-72',
      rg: '33.874.271-2',
      data_nasc: '24/08/1946',
      sexo: 'Masculino',
    },
  ];

  let renderCadastros = (banco) => {
    for (let i = 0; i < bancoDeCadastros.length; i++) {
      let novaTabela = `<tr id="${banco[i].id}">
                  <td>${banco[i].id}</td>
                  <td>${banco[i].nome}</td>
                  <td>${banco[i].cpf}</td>
                  <td>${banco[i].rg}</td>
                  <td>${banco[i].data_nasc}</td>
                  <td>${banco[i].sexo}</td>
                  <td class="material-icons" data-id="${banco[i].id}">delete_forever</td>
              </tr>`;

      tabela.innerHTML += novaTabela;
    }
  };

  botaoInserirPessoa.addEventListener('click', () => {
    let id = campoId.value;
    let nome = campoNome.value;
    let cpf = campoCpf.value;
    let rg = campoRg.value;
    let nascimento = campoNascimento.value;
    let sexo = campoSexo.value;

    let novaTabela = `<tr id="${id}">
              <td>${id}</td>
              <td>${nome}</td>
              <td>${cpf}</td>
              <td>${rg}</td>
              <td>${nascimento}</td>
              <td>${sexo}</td>
              <td class="material-icons" data-id="${id}">delete_forever</td>
          </tr>`;

    //Limpa os campos do formulário
    campoId.value = '';
    campoNome.value = '';
    campoCpf.value = '';
    campoRg.value = '';
    campoNascimento.value = '';
    campoSexo.value = '';

    //Inclui os novos dados na tabela
    tabela.innerHTML += novaTabela;

    //Atualiza o banco de cadatros
    let novoCadastro = {
      id: id,
      nome: nome,
      cpf: cpf,
      rg: rg,
      data_nasc: nascimento,
      sexo: sexo,
    };
    
    addEventToMaterialIcons();
    
    bancoDeCadastros.push(novoCadastro);
  });

  renderCadastros(bancoDeCadastros);

  function addEventToMaterialIcons() {
    let botaoExcluir = document.querySelectorAll('.material-icons');

    botaoExcluir.forEach((el) => {
      el.addEventListener('click', () => {
        const idLinha = el.getAttribute('data-id');

        document.getElementById(`${idLinha}`).remove();
      });
    });
  }

  addEventToMaterialIcons();
* {
        font-size: 16px;
        margin: 0;
        padding: 0;
        font-family: Roboto;
        color: rgb(51, 51, 51);
      }

      /*Container principal*/
      #container {
        text-align: center;
        align-items: center;
        margin: 15px;
      }

      /*Campos do formulário*/
      #inserirDados div,
      input,
      button {
        margin: 5px 0 5px 0;
        padding: 3px;
      }

      #inserirDados input {
        width: 120px;
      }

      #inserirDados button {
        width: 60px;
        border: 0;
        border-radius: 8px;

        color: rgb(248, 248, 248);
        background-color: rgb(38, 98, 230);

        transition: 0.3s;
      }
      #inserirDados button:hover {
        cursor: pointer;
        background-color: rgb(42, 89, 190);
        transition: 0.3s;
      }

      /*Tabela*/
      #cadastrosPessoa {
        margin: auto;
        border-collapse: collapse;
        text-align: left;
      }

      #cadastrosPessoa th {
        border: 0;
      }

      #cadastrosPessoa td {
        border: 1px solid rgb(77, 226, 122);
        font-weight: normal;

        padding: 3px;
      }

      #cadastrosPessoa .material-icons {
        cursor: pointer;

        transition: 0.3s;
      }

      #cadastrosPessoa .material-icons:hover {
        color: tomato;
        transition: 0.3s;
      }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Listagem de pessoas</title>
  </head>
  <body>
    <div id="container">
      <div id="inserirDados">
        <h1>Adicionar colaborador</h1>
        <input type="text" name="id" id="id" placeholder="ID" />
        <input type="text" name="nome" id="nome" placeholder="Nome" />
        <input type="text" name="cpf" id="cpf" placeholder="CPF" />
        <input type="text" name="rg" id="rg" placeholder="RG" />
        <input
          type="text"
          name="dataNascimento"
          id="dataNascimento"
          placeholder="Nascimento"
        />
        <input type="text" name="sexo" id="sexo" placeholder="Sexo" />
        <br />
        <button id="inserirPessoa">OK</button>
      </div>
    </div>

    <table id="cadastrosPessoa">
      <tr>
        <th>ID</th>
        <th>Nome</th>
        <th>CPF</th>
        <th>RG</th>
        <th>Nascimento</th>
        <th>Sexo</th>
        <th></th>
      </tr>
    </table>
  </body>
  
  <link rel="stylesheet" href="/main.css" />
  <link
    href="https://fonts.googleapis.com/icon?family=Material+Icons"
    rel="stylesheet"
  />
</html>

What differs from the other answer, besides logic, is the fact that the click event is related only to the class element .material-icons and not the whole document. Obviously, this is one more solution out of many possible, as well as the other answer.

  • Hello, your help has been of great help! @Cmte Cardinal I chose to make my code the style you sent, since your idea was the same as mine initially, but I could not put it into practice. However, I have a problem with the code, which is when I enter a new record. by doing this, the delete action no longer works, you would know what might be?

  • @Diegosousa I understood, but it’s easy to solve. I updated my answer. See if it’s good for Oce.

  • perfect, corrected and functioning as expected. A doubt only, because creating the button capturing the material icons can not be done outside the function? only works if inside it.

  • Because Voce created a new table element and when it does, Voce calls a function here: botaoInserirPessoa.addEventListener('click, () => {...}) Only what is within this function will be executed, then to add an event for the material icons, Voce has to call addEventToMaterialIcons to update events for all delete buttons, including new ones that are added by fomulario.

  • 1

    Thank you very much, it was of great help!!! @Cmte Cardinal

1

I would recommend a addEventListener of click in the entire document, clicking it will take the class attribute of the element clicked with a target and getAttribute(), if it’s material-icons, he’ll get id of its parent element, using the parentNode(which is the line) and, that is, using the parentNode.id he’s gonna get the id of the parent element, and with a remove() it removes the element.

    let botaoInserirPessoa = document.querySelector("#inserirPessoa");
    let tabela = document.querySelector("#cadastrosPessoa")

    let campoId = document.querySelector("#id")
    let campoNome = document.querySelector("#nome")
    let campoCpf = document.querySelector("#cpf")
    let campoRg =document.querySelector("#rg")
    let campoNascimento = document.querySelector("#dataNascimento")
    let campoSexo = document.querySelector("#sexo")

    let botaoExcluir = document.querySelector(".material-icons")

    let bancoDeCadastros = [
        {
          "id": 1,
          "nome": "Francisca Julia da Costa",
          "cpf": "457.696.936-65",
          "rg": "47.360.897-2",
          "data_nasc": "23/03/1944",
          "sexo": "Feminino"
        },
        {
          "id": 2,
          "nome": "Noah Felipe Silva",
          "cpf": "956.531.431-70",
          "rg": "40.974.782-8",
          "data_nasc": "11/07/1964",
          "sexo": "Masculino"
        },
        {
          "id": 3,
          "nome": "Alícia Rosângela Melo",
          "cpf": "066.291.353-18",
          "rg": "36.214.141-1",
          "data_nasc": "18/02/1978",
          "sexo": "Feminino"
        },
        {
          "id": 4,
          "nome": "Cristiane Renata Ana das Neves",
          "cpf": "946.074.401-08",
          "rg": "32.301.736-8",
          "data_nasc": "10/05/1966",
          "sexo": "Feminino"
        },
        {
          "id": 5,
          "nome": "Priscila Benedita Vanessa Ferreira",
          "cpf": "888.282.394-68",
          "rg": "44.524.670-4",
          "data_nasc": "15/11/1966",
          "sexo": "Feminino"
        },
        {
          "id": 6,
          "nome": "Bianca Carolina Nunes",
          "cpf": "484.323.140-13",
          "rg": "44.466.563-8",
          "data_nasc": "16/03/1948",
          "sexo": "Feminino"
        },
        {
          "id": 7,
          "nome": "Yuri Vicente Manuel Silveira",
          "cpf": "250.111.093-56",
          "rg": "18.597.361-9",
          "data_nasc": "05/09/1974",
          "sexo": "Masculino"
        },
        {
          "id": 8,
          "nome": "Melissa Alessandra Barros",
          "cpf": "446.675.916-25",
          "rg": "25.598.673-7",
          "data_nasc": "13/01/2000",
          "sexo": "Feminino"
        },
        {
          "id": 9,
          "nome": "Márcia Daniela Lara da Cruz",
          "cpf": "932.803.826-02",
          "rg": "40.653.176-6",
          "data_nasc": "04/06/1986",
          "sexo": "Feminino"
        },
        {
          "id": 10,
          "nome": "Filipe Anderson Rafael Assis",
          "cpf": "704.869.005-41",
          "rg": "39.383.334-3",
          "data_nasc": "19/11/1995",
          "sexo": "Masculino"
        },
        {
          "id": 11,
          "nome": "Luís Vinicius Sebastião Jesus",
          "cpf": "035.960.588-56",
          "rg": "29.915.692-8",
          "data_nasc": "23/04/1965",
          "sexo": "Masculino"
        },
        {
          "id": 12,
          "nome": "Cecília Caroline Nascimento",
          "cpf": "034.396.672-78",
          "rg": "48.673.066-9",
          "data_nasc": "04/02/1951",
          "sexo": "Feminino"
        },
        {
          "id": 13,
          "nome": "Raimunda Sandra Ferreira",
          "cpf": "757.187.891-85",
          "rg": "21.189.806-5",
          "data_nasc": "17/11/1974",
          "sexo": "Feminino"
        },
        {
          "id": 14,
          "nome": "Andreia Isabelly Juliana Melo",
          "cpf": "736.348.985-85",
          "rg": "24.677.018-1",
          "data_nasc": "11/10/1963",
          "sexo": "Feminino"
        },
        {
          "id": 15,
          "nome": "Nicolas Bernardo Moura",
          "cpf": "061.370.865-26",
          "rg": "16.302.343-8",
          "data_nasc": "08/06/1989",
          "sexo": "Masculino"
        },
        {
          "id": 16,
          "nome": "Diego Benjamin Tiago da Luz",
          "cpf": "991.152.443-42",
          "rg": "38.315.100-4",
          "data_nasc": "04/06/1990",
          "sexo": "Masculino"
        },
        {
          "id": 17,
          "nome": "Marlene Emanuelly Yasmin Cavalcanti",
          "cpf": "781.233.625-52",
          "rg": "21.068.742-3",
          "data_nasc": "15/10/1961",
          "sexo": "Feminino"
        },
        {
          "id": 18,
          "nome": "Vanessa Isabela da Luz",
          "cpf": "872.138.490-85",
          "rg": "44.289.193-3",
          "data_nasc": "05/09/1982",
          "sexo": "Feminino"
        },
        {
          "id": 19,
          "nome": "Camila Flávia Vera Mendes",
          "cpf": "790.524.518-77",
          "rg": "40.847.994-2",
          "data_nasc": "01/07/1952",
          "sexo": "Feminino"
        },
        {
          "id": 20,
          "nome": "Luana Lívia Lara Campos",
          "cpf": "532.901.056-01",
          "rg": "14.732.946-2",
          "data_nasc": "19/08/1981",
          "sexo": "Feminino"
        },
        {
          "id": 21,
          "nome": "Josefa Nina Galvão",
          "cpf": "379.743.833-80",
          "rg": "13.878.690-2",
          "data_nasc": "27/01/1943",
          "sexo": "Feminino"
        },
        {
          "id": 22,
          "nome": "Natália Isabelly Silvana da Paz",
          "cpf": "454.172.867-29",
          "rg": "22.986.096-5",
          "data_nasc": "17/09/1980",
          "sexo": "Feminino"
        },
        {
          "id": 23,
          "nome": "Amanda Sebastiana Vieira",
          "cpf": "703.941.038-90",
          "rg": "50.251.196-5",
          "data_nasc": "08/06/1960",
          "sexo": "Feminino"
        },
        {
          "id": 24,
          "nome": "Noah Pedro Alves",
          "cpf": "074.733.106-58",
          "rg": "32.110.015-3",
          "data_nasc": "14/08/1992",
          "sexo": "Masculino"
        },
        {
          "id": 25,
          "nome": "Giovana Camila da Conceição",
          "cpf": "418.746.840-49",
          "rg": "35.520.215-3",
          "data_nasc": "25/06/1947",
          "sexo": "Feminino"
        },
        {
          "id": 26,
          "nome": "Pietro Joaquim Emanuel Gonçalves",
          "cpf": "003.502.230-25",
          "rg": "12.099.068-4",
          "data_nasc": "21/04/1999",
          "sexo": "Masculino"
        },
        {
          "id": 27,
          "nome": "Tereza Kamilly Mariana Porto",
          "cpf": "050.946.705-90",
          "rg": "39.830.941-3",
          "data_nasc": "16/06/1959",
          "sexo": "Feminino"
        },
        {
          "id": 28,
          "nome": "Caroline Emanuelly Lívia Moreira",
          "cpf": "673.831.546-57",
          "rg": "24.561.727-9",
          "data_nasc": "09/04/1948",
          "sexo": "Feminino"
        },
        {
          "id": 29,
          "nome": "Gabriel Ricardo da Paz",
          "cpf": "829.270.172-98",
          "rg": "30.407.114-6",
          "data_nasc": "24/03/1980",
          "sexo": "Masculino"
        },
        {
          "id": 30,
          "nome": "Giovanni Igor Augusto Pires",
          "cpf": "584.880.490-72",
          "rg": "33.874.271-2",
          "data_nasc": "24/08/1946",
          "sexo": "Masculino"
        }
      ]

    let renderCadastros = banco =>{
        
        for (let i=0; i<bancoDeCadastros.length; i++){    
            
            let novaTabela = `<tr id="${banco[i].id}">  
                                <td>${banco[i].id}</td>
                                <td>${banco[i].nome}</td>
                                <td>${banco[i].cpf}</td>
                                <td>${banco[i].rg}</td>
                                <td>${banco[i].data_nasc}</td>
                                <td>${banco[i].sexo}</td>
                                <td class="material-icons">delete_forever</td>
                            </tr>`
                            
            tabela.innerHTML += novaTabela
        }
    }

    botaoInserirPessoa.addEventListener("click", ()=>{
        
        let id = campoId.value
        let nome = campoNome.value
        let cpf = campoCpf.value
        let rg = campoRg.value
        let nascimento = campoNascimento.value
        let sexo = campoSexo.value

        let novaTabela = `<tr id="${id}">  
                            <td>${id}</td>
                            <td>${nome}</td>
                            <td>${cpf}</td>
                            <td>${rg}</td>
                            <td>${nascimento}</td>
                            <td>${sexo}</td>
                            <td class="material-icons">delete_forever</td>
                        </tr>`          
        
        //Limpa os campos do formulário                
        campoId.value = ""
        campoNome.value = ""
        campoCpf.value = ""
        campoRg.value = ""
        campoNascimento.value = "" 
        campoSexo.value = ""
        
        //Inclui os novos dados na tabela
        tabela.innerHTML += novaTabela

        //Atualiza o banco de cadatros
        let novoCadastro = {
            "id": id,
            "nome": nome,
            "cpf": cpf,
            "rg": rg,
            "data_nasc": nascimento,
            "sexo": sexo
        }

        bancoDeCadastros.push(novoCadastro)
    })

    renderCadastros(bancoDeCadastros)

    document.addEventListener('click', (e) =>{
       if (e.target.getAttribute('class') == 'material-icons'){
       alert(e.target.parentNode.id)
       document.getElementById(e.target.parentNode.id).remove()
    
    }

})
    /*Root*/
    *{
        font-size: 16px;
        margin: 0;
        padding: 0;
        font-family: Roboto;
        color: rgb(51, 51, 51);
    }

    /*Container principal*/
    #container{
        text-align: center;
        align-items: center;
        margin: 15px;
    }

    /*Campos do formulário*/
    #inserirDados div, input, button{
        margin: 5px 0 5px 0;
        padding: 3px;
    }

    #inserirDados input{
        width: 120px;
    }

    #inserirDados button{
        width: 60px;
        border: 0;
        border-radius: 8px;
        
        color: rgb(248, 248, 248);
        background-color: rgb(38, 98, 230);

        transition: .3s;
    }
    #inserirDados button:hover {
        cursor: pointer;
        background-color: rgb(42, 89, 190);
        transition: .3s;
    }

    /*Tabela*/
    #cadastrosPessoa{
        margin: auto;
        border-collapse: collapse;
        text-align: left;
    }

    #cadastrosPessoa th{
        border: 0;
    }

    #cadastrosPessoa td{
        border: 1px solid  rgb(77, 226, 122);
        font-weight: normal;

        padding: 3px;
    }

    #cadastrosPessoa .material-icons{
        cursor:pointer;
        
        transition: .3s;
    }

    #cadastrosPessoa .material-icons:hover{
        
        color: tomato;
        transition: .3s;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Listagem de pessoas</title>
    </head>
    <body>
        
        <div id="container">
            <div id="inserirDados">
                <h1>Adicionar colaborador</h1>
                <input type="text" name="id" id="id" placeholder="ID">
                <input type="text" name="nome" id="nome" placeholder="Nome">
                <input type="text" name="cpf" id="cpf" placeholder="CPF">
                <input type="text" name="rg" id="rg" placeholder="RG">
                <input type="text" name="dataNascimento" id="dataNascimento" placeholder="Nascimento">
                <input type="text" name="sexo" id="sexo" placeholder="Sexo">
                <br>
                <button id="inserirPessoa">OK</button>
            </div>
        </div>
            
        <table id="cadastrosPessoa">
            <tr>
                <th>ID</th>
                <th>Nome</th>
                <th>CPF</th>
                <th>RG</th>
                <th>Nascimento</th>
                <th>Sexo</th>
                <th></th>
            </tr>
        </table>
            
    </body>

    <script src="/scripts.js"></script>

    <link rel="stylesheet" href="/main.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
    rel="stylesheet">

    </html>

Code added:

document.addEventListener('click', (e) =>{
    if (e.target.getAttribute('class') == 'material-icons'){
        alert(e.target.parentNode.id)
        document.getElementById(e.target.parentNode.id).remove()
}
})

You can do with some variables too if you feel better:

document.addEventListener('click', (e) =>{
    if (e.target.getAttribute('class') == 'material-icons'){
        alert(e.target.parentNode.id)
        var linha = document.getElementById(e.target.parentNode.id)
        linha.remove()
}
})

PS: I put one alert just to show the id and confirm that it’s working I hope I’ve helped

  • 1

    thank you very much!

Browser other questions tagged

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