Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!