Home > Software design >  Value from addEventListeners e.traget
Value from addEventListeners e.traget

Time:04-18

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 >
  <li  id="1"></li>
  <li  id="2"></li>
  <li  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?

CodePudding user response:

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);
});

CodePudding user response:

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>
  • Related