Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

48
Vistas
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?

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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);
});
7 months ago · Juan Pablo Isaza Denunciar

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>
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.