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);
});
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With