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

287
Views
How to know which querySelectorAll item got clicked

I have this code structure:

let items = document.querySelectorAll('.item')

items.forEach(addEventListener (
    'click', function () {
        // code that will get item that got clicked
    }
))

Item's HTML looks like this:

   <div class="item" data-value="water">water</div>
   <div class="item" data-value="air">air</div>
   <div class="item" data-value="fire">fire</div>

And I want to have function that when you click on any item, item's datavalue attribute must show in console or anywhere. I just must know which element got clicked.

I tried this

items.forEach(addEventListener (
    'click', function () {
        console.log(this.getAttribute('data-value'))
    }
))

But it didn't work..

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try like following:

let items = document.querySelectorAll('.item')
items.forEach(item =>
  item.addEventListener (
    'click', function () {
        console.log(event.target.getAttribute('data-value'))
    }
))
<div class="item" data-value="water">water</div>
   <div class="item" data-value="air">air</div>
   <div class="item" data-value="fire">fire</div>

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!