I have several structures that follow a unique style:
<div data-id="1">
<div>
<button>Descobrir é o data-id desta estrutura</button>
</div>
</div>
I have several structures that follow a unique style:
<div data-id="1">
<div>
<button>Descobrir é o data-id desta estrutura</button>
</div>
</div>
I suggest using .closest()
like this:
$('button').on('click', function () {
var target = $(this).closest('[data-id]');
alert(target.data('id'));
});
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.
You can do this using parent()
and then data()
:
$('button').on('click', function(){
alert($(this).parent().parent().data('id'));
});