• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

272
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 3 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 3 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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error