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
Value from addEventListeners e.traget

Is it possible to store a value as id from EventListener? I need an ID from this list when I click on item.

This is what I've tried:

    <ul class="list">
      <li class="item-list" id="1"></li>
      <li class="item-list" id="2"></li>
      <li class="item-list" id="3"></li>
    </ul>
    
    <script type="text/javascript">
        list.addEventListener("click", function (e) {
            let podlistIndex;
            if (e.target.classList.contains("item-list")) {
                podlistIndex= e.target.getAttribute("id");
            }
    
            console.log(podlistIndex);
        });
    </script>

When the item is clicked, I can get value as an id, but the value is lost when I click somewhere else. How can I store the value?

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

0

Place the variable outside the event handler

let podlistIndex;
list.addEventListener("click", (e) => {
   if (e.target.classList.contains("item-list")) {
      podlistIndex = e.target.getAttribute("id");
   }

   console.log(podlistIndex);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Make an array outside the function and fill it up every single click you make. This way it won't overwrite any id.

<script>
const ids = [];
let list = document.querySelector('.list');
list.addEventListener("click", function (e) {
   let podlistIndex;

       if (e.target.classList.contains("item-list")) {
        podlistIndex= e.target.getAttribute("id");
        ids.push(podlistIndex);
      }

   console.log(ids);
   });
</script>
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