Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference data from a parent element using jQuery?

Tags:

jquery

I would like to reference the data-post-id of a parent div when clicking on an achor:

<div data-post-id="5">
 <a data-vote-type="1">Like</a>
 <a data-vote-type="2">Dislike</a>
</div>

To reference the vote-type, I can do this:

var voteData = '&voteType=' + $(this).data('vote-type')

But I would also like to include the post-id in the voteData var. I'm not sure how to do this however. I have multiple posts on the page, each with their own like/dislike buttons!

like image 274
Mohamad Avatar asked Dec 17 '22 19:12

Mohamad


2 Answers

You're looking for $(this).parent().

If you need a specific ancestor, you should call $(this).closest('selector'), which finds the innermost ancestor that matches a selector.

like image 87
SLaks Avatar answered Dec 28 '22 22:12

SLaks


var voteData = '&voteType=' + $(this).data('vote-type') + '&postId=' + $(this).parent().data('post-id');
like image 22
Ben Avatar answered Dec 28 '22 23:12

Ben