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

345
Views
jQuery - how to get data name?

I have many div with "data-value" attribute. But only one with class name ".selected". I need to make selector with both. Data + class name.

How to make selector with data atribute and class name ?

HTML

<div data-value="x">Click Me!</div>
<div data-value="y">Click Me!</div>
<div class='selected' data-value="z">Click Me!</div>
<div data-value="w">Click Me!</div>

jQuery

alert( $("div[data-value] .selected").data('value') );  // this is wrong way...
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

There are two ways to get data attribute:

$(".selected").attr('data-value');  // It works for all type of custom attribute

or

$(".selected").data('value');  // This one is specially for data attribute
about 4 years ago · Santiago Trujillo Report

0

You can do that with jQuery's attr():

alert($('div').attr('data-value'));

But, since there will me more than one divs, better give each one a class (to be more specific):

<div class="clickable" data-value="x">Click Me!</div>
<div class="clickable" id="second" data-value="y">Click Me!</div>
<div class='selected clickable' data-value="z">Click Me!</div>
<div class="clickable" data-value="w">Click Me!</div>

and the jQuery will be:

$('div.clickable').on('click', function(){

    alert($(this).attr('data-value'));

});

Fiddle here: https://jsfiddle.net/hpb5u62e/

about 4 years ago · Santiago Trujillo Report

0

check working example.I have added click event for button

$(document).ready(function(){
    $("button").click(function(){
      alert( $(".selected").attr('data-value') );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-value="x">Click Me!</div>
<div data-value="y">Click Me!</div>
<div class='selected' data-value="z">Click Me!</div>
<div data-value="w">Click Me!</div>
<button>Click me</button>

about 4 years ago · Santiago Trujillo 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!