Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
How I can make event listener(change) fot items with vanilla JS

How do I run the same action for each event. When the user selects an option, I need to show a table. And when they select another, show another table. But the tables were getting shown one by one. So I added an action for removing, but now the table only appears half the time. How can I make a select event lister, that does not disappear after the second click and not repeat tables

function getTableRegion(select, divResutl) {
    select.addEventListener('change', function (ev) {
        cleanMessage(divResutl);
        console.log(ev)
        if (document.getElementById('table')) {
            divResutl.removeChild(document.getElementById('table'))
        } else {
            let tbody = document.createElement('tbody');
            let table = document.createElement('table');
            table.id = 'table';
            table.setAttribute('style', 'display:table');
            tbody.innerHTML = `<tr><th>Country name</th>
                                 <th>Capital</th><th>World region</th><th>Languages</th>
                                  <th>Area</th><th>Flag </th></th></tr>`;
            table.append(tbody);
            divResutl.append(table);
        }
    })
}

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is no reason to do if/else. If it exists, remove it and add the next.

function getTableRegion(select, divResutl) {
  select.addEventListener('change', function(ev) {
    cleanMessage(divResutl);
    console.log(ev)
    if (document.getElementById('table')) {
      document.getElementById('table').remove();
    }
    let tbody = document.createElement('tbody');
    let table = document.createElement('table');
    table.id = 'table';
    tbody.innerHTML = `<tr><th>Country name</th>
                                     <th>Capital</th><th>World region</th><th>Languages</th>
                                      <th>Area</th><th>Flag </th></th></tr>`;
    table.append(tbody);
    divResutl.append(table);

  })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda