3

I need data-offerId of parent div but it's not working properly. Please suggest me.

HTML

<div class="rows" data-offerid="123487 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div>
<div class="rows" data-offerid="123486 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div>

Jquery:

 $('.clear-row').click(function(){
     var offers = $('.clear-row').parent().attr('data-offerid');
     console.log(offers);
 });
jinfy
  • 147
  • 1
  • 12

4 Answers4

6

Inside the handler, you should be using this not repeating the selector .clear-row

$('.clear-row').click(function(){
   var offers = $(this).parent().attr('data-offerid');
   console.log(offers);
});

You can also use data() instead of attr()

var offers = $(this).parent().data('offerid');
Jamiec
  • 133,658
  • 13
  • 134
  • 193
2

Here you go with one more way using jQuery closest method https://jsfiddle.net/464g5hzq/

$('.clear-row').click(function(){
  var offers = $(this).closest('div.rows').data('offerid');
  console.log(offers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rows" data-offerid="123487 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div>
<div class="rows" data-offerid="123486 ">15<span class="mth">.– /mth</span><span class="clear-row"></span></div>

Instead of using .attr to get the data attribute, please use .data(attribute-name); if you have data attribute like data-offerid.

Hope this will be useful to you.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
1

Use this inside your click event, to target the cleararrow element your clicked on

$(this).parent().attr('data-offerid')

$('.clear-row').click(function() {
  var offers = $(this).parent().attr('data-offerid');
  console.log(offers);
});

Working example

$('.clear-row').click(function() {
  var offers = $(this).parent().attr('data-offerid');
  console.log(offers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rows" data-offerid="123487 ">15<span class="mth">.– /mth</span><span class="clear-row">clear</span></div>
<div class="rows" data-offerid="123486 ">15<span class="mth">.– /mth</span><span class="clear-row">clear</span></div>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

Try this way:

$('.clear-row').click(function(){
    var offers = $(this).parent().attr('data-offerid');
    console.log(offers);
});

//OR

var offers = this.parentNode.getAttribute("data-offerid");   // plain javascript

Helper Link to understand: parent

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
  • WHy did you switch from jquery back to vanilla JS? And in any case the vanilla version doesnt do anything like the jquery version – Jamiec Sep 01 '17 at 08:36
  • Just for a reference sir. The user has added `javascript` in question tag so I had just added it here. – always-a-learner Sep 01 '17 at 08:37