Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

47
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?

7 months 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);
});
7 months 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>
7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.