jmenezes
jmenezes

Reputation: 1926

Getting a data attributes value from a div one step above

In the following scenario, how do i get the value of data-kush when I click on the readMore link?

There are more products displayed the same way, and I need to display the value of the data-kush that is above the readMore link that is clicked.

http://jsfiddle.net/fge72ma9/

<div>
<div class="product itemName" data-kush="9a7e96cb9b72fb8c526961e7366bf1a8">
    Norwegian Kush
</div>

<div class="moreInfo">
    <span class="readMore">Click to read more...</span>
</div>
</div>

<div>
<div class="product itemName" data-kush="fb8c526961e7366bf1a8">
    Bubba Kush
</div>

<div class="moreInfo">
    <span class="readMore">Click to read more...</span>
</div>
</div>

jQuery

$('.readMore').click(function() {
    alert($(this).closest('.itemName').data('kush'));
});

The above is what I thought would work, but does not. Can you help?

Upvotes: 0

Views: 57

Answers (2)

collab-with-tushar-raj
collab-with-tushar-raj

Reputation: 1287

For each element in the set , .closest() get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

In your Question , you did this

 $(this).closest('.itemName')

as .itemName is not the ancestor of .readMore nor it matches with the selector .readMore

For more you can check API

This will provide you an Exception. So you need to access the right element by doing like this

 $('.readMore').click(function () {
      alert($(this).closest('div').siblings('.itemName').attr('data-kush'));
 });

FIDDLE

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

it is the previous sibling of current element's parent.

So

$('.readMore').click(function() {
  alert($(this).parent().prev('.itemName').data('kush'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="product itemName" data-kush="9a7e96cb9b72fb8c526961e7366bf1a8">
    Norwegian Kush
  </div>

  <div class="moreInfo">
    <span class="readMore">Click to read more...</span>
  </div>
</div>

<div>
  <div class="product itemName" data-kush="fb8c526961e7366bf1a8">
    Bubba Kush
  </div>

  <div class="moreInfo">
    <span class="readMore">Click to read more...</span>
  </div>
</div>

.closest() is used for getting an ancestor element, here since the target element is not an ancestor it won't work

Upvotes: 2

Related Questions