0

I've got buttons with different data-category attributes. How can I get the data-category by referring its id?

<button id="fru52" data-category="lychee">Fruit</button>
<button id="veg17" data-category="veggie">Veggies</button>
<button id="des29" data-category="apple-pie">Dessert</button>

$('#getdata').on('click', function(){
    //how do I get the data-category of #veg17 ?
});
Becky
  • 5,217
  • 9
  • 33
  • 68

1 Answers1

5

try this:-

$('#getdata').on('click', function(){
//how do I get the data-category of #veg17 ?
 var dataid=$('#veg17').attr('data-category');
//or
  var dataid=$('#veg17').data('category');
});

or on click of #veg17

 $('#veg17 ').on('click', function(){
//how do I get the data-category of #veg17 ?
 var dataid=$(this).attr('data-category');
//or
  var dataid=$(this).data('category');
});
Mohit Kumar
  • 9,065
  • 2
  • 27
  • 43
  • beautiful. what would be the better option `.attr` or `.data` ? – Becky Jun 30 '15 at 13:48
  • 1
    Thanks indeed, I didn't realize there was that many differences. so basically using `data()` is the best and most common practice, but in some specific cases you might need `attr()`... – Laurent S. Jun 30 '15 at 13:55