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

215
Views
How to get data from a specific class in javascript?

HTML code

$(".values").click(function(){
  $(".values").each(function(){
    var value = $(this).data('value');
    alert(value);
  });
})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<p class="values" data-value="1">Value 1</p>
<p class="values" data-value="2">Value 2</p>
<p class="values" data-value="3">Value 3</p>
<p class="values" data-value="4">Value 4</p>
<p class="values" data-value="5">Value 5</p>

The problem is when i click in a specific p tag he alerts all the p tags with the data values, and i need that the click event trigger one alert with the specific data value.

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

0

Just remove the .each loop.

$(".values").click(function(){
    var value = $(this).data('value');
    alert(value);
})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<p class="values" data-value="1">Value 1</p>
<p class="values" data-value="2">Value 2</p>
<p class="values" data-value="3">Value 3</p>
<p class="values" data-value="4">Value 4</p>
<p class="values" data-value="5">Value 5</p>

about 4 years ago · Juan Pablo Isaza Report

0

When you are using jQuery selection you don't need to loop to each selected item to attach event handler. jQuery will handle that internaly you will just have to use $(this) to target the item which is clicked at a given time

$('.values').click(function(){
    console.log($(this).data('value'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="values" data-value="1">Value 1</p>
<p class="values" data-value="2">Value 2</p>
<p class="values" data-value="3">Value 3</p>
<p class="values" data-value="4">Value 4</p>
<p class="values" data-value="5">Value 5</p>

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!