Get parent div attributes through child elements

7

I have several structures that follow a unique style:

<div data-id="1">
 <div>
   <button>Descobrir é o data-id desta estrutura</button> 
 </div>
</div>

asked by anonymous 05.08.2015 / 21:22

2 answers

12

I suggest using .closest() like this:

$('button').on('click', function () {
    var target = $(this).closest('[data-id]');
    alert(target.data('id'));
});

jsFiddle: link

The .closest() rises in the DOM for the first element that the selector indicates / searches. The '[data-id]' selector means "an element with the data-id attribute, regardless of its value, as long as it has the attribute".

This way you avoid code of type .parent().parent() which is difficult to maintain and know which element applies.

    
05.08.2015 / 21:32
3

You can do this using parent() and then data() :

$('button').on('click', function(){
    alert($(this).parent().parent().data('id'));
});
    
05.08.2015 / 21:26