How to reference data from parent using jQuery?

I would like to refer to the data-post-id of the parent div when clicking on achore:

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

To refer to the type of voting, I can do this:

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

But I would also like to include post-id in voteData var. However, I do not know how to do this. I have several posts on the page, each of which has its own dislike buttons.

+4
source share
2 answers

You are looking for $(this).parent() .

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

+11
source
 var voteData = '&voteType=' + $(this).data('vote-type') + '&postId=' + $(this).parent().data('post-id'); 
+1
source

Source: https://habr.com/ru/post/1332170/


All Articles