Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get parent div attribute values in jquery?

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);
 });
like image 724
jinfy Avatar asked Sep 16 '25 02:09

jinfy


2 Answers

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');
like image 153
Jamiec Avatar answered Sep 17 '25 15:09

Jamiec


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.

like image 38
Shiladitya Avatar answered Sep 17 '25 16:09

Shiladitya